Archive
This post is archived and may contain outdated information. It has been set to 'noindex' and should stop showing up in search results.
How To Use CSS Linear Gradient Background With Solid Color Fallback
Jul 2, 2014Web DevelopmentComments (0)
CSS gradients are a great way to reduce HTTP requests and file size. Their main downside is that Internet Explorer 9 and earlier do not support them. If IE9 and earlier are a small-enough percentage of your traffic, a solid color fallback is the simplest and most elegant solution.

Note: IE9 and earlier account for less than 2% of this site's visitors (your site may be different). Just make sure your solid color fallback looks good.


The CSS Script


Since a CSS gradient is an image generated by the browser, and not a color, you can assign the color and image separately, and IE9 and earlier will simply ignore the gradient image. This is tested all the way back to IE5:

.my-element {
background-color: #222;
background-image: -webkit-linear-gradient(top, #111, #333);
background-image: linear-gradient(to bottom, #111, #333);
}

The first property is the solid color background. The next property is the -webkit prefixed gradient, which is mostly for older versions of Android and iOS browsers. The last property is the CSS3 standard gradient, which is supported by all modern browsers.

Note: There are other prefixes, such as -o for older versions of Opera, and filters for older versions of Internet Explorer. These are usually unnecessary CSS bloat to support a very small percentage of browsers, but if your analytics show a large percentage of these browsers you may want to support them.


More Compact CSS


You can make the above example more compact by using the CSS background shorthand:

.my-element {
background: #222;
background: -webkit-linear-gradient(top, #111, #333);
background: linear-gradient(0deg, #333, #111);
}

This will still work all the way back to IE6, though may fail in IE5 (which you probably don't care about). Also notice that I used "0deg" for the direction in the CSS3 gradient. This uses fewer characters than "to bottom", though the start and end colors have to be swapped. You could also use "180deg" here and not swap the start and end colors.
Comments (0)
Add a Comment
No comments yet