Helping you solve those tough coding problems!

Creating a Background Gradient with CSS Creating a Background Gradient with CSS

Published on Mar 15, 2019 by Jamie Munro

To create a gradient background image with CSS, you need two things: a starting color and a bottom color. It would also be handy to have a potential "fall back" background color that sits somewhere in the middle of the two.





Defining the Gradient



For the purpose of this example, here is the start HEX color value: #12496f and here is the end HEX color value: #1e70aa. The fall back background color will be: #185c8c. Now that I have my colors, here is the CSS required to create a gradient background. In the following example, I want the background color to appear for my header 1 tags (the title of my articles).


h1 {
background: #185c8c;
background-image: -moz-linear-gradient(top, #12496f, #1e70aa);
background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #12496f),color-stop(1, #1e70aa));
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#CC12496f, endColorstr=#CC1e70aa);

padding: 6px;
color: #FFF;
}


As you might notice in the above example, the start and end colors are repeated three times. The reason for this is that each of the major browsers implement gradients in a different fashion and our CSS pays the price for it and we need to include each of the types.

I'm sure you guessed which browser each is for, but in case not, the first one: -moz-linear-gradient is for Firefox and other Mozilla based browsers. The second one: -webkit-gradient, is for webkit based browsers such as Google Chrome and Safari. The third one is for Internet Explorer where a DXImageTransform function is used to create the gradient.

The next time a designer decides that a gradient should be used for a background image, have no fear because you no longer need to chop it up and use a background image. Instead a few lines of CSS3 can replace the need altogether for the image helping to improve the speed of your webpages!

Tags: CSS | CSS

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP