Cross-browser CSS gradients

Firefox 3.6 is very close to release (it’s currently in its first release candidate) and once it lands every browser (even IE) has support for gradients in pure CSS.

This will be incredibly useful. As we add more and more JavaScript and rich media to web pages, performance is affected. One easy way we can mitigate the effect this has is to leverage the power of CSS to reduce the number of background images we use; for instance for rounded corners and gradients. Border-radius is still not implemented in IE (rumoured to be included in IE12 when it’s out in 2043) but gradients are, and we should all start using them now.

Example

Here’s a real-life example. This is just a link; this style can be applied to any element; <button>, <input type=”submit”>. <a>, whatever.

I’m a button

Dependent on what browser you are using, it will look different.

How it looks cross-browser

Firefox 3.5

CSS3 Buttons in FF3.5

Firefox 3.6

CSS3 buttons in FF3.6

Internet Explorer

CSS3 buttons in IE

Safari and Chrome

CSS3 buttons in WebKit

The CSS

.sexybutton {
  background: #DEDEDE;
  background: -moz-linear-gradient(top, #FFF, #888);
  background: -webkit-gradient(linear, left top, left bottom, from(#FFF), to(#888));
  border: 1px solid #D6D6D6;
  color: #666;
  display: inline-block;
  filter: progid:DXImageTransform.Microsoft.Gradient(StartColorStr='#FFFFFF', EndColorStr='#888888');
  font: bold 1.3em/22px Helvetica, Arial, sans-serif;
  height: 22px;
  padding: 0 10px;
  text-decoration: none;
  text-shadow: 0 1px 0 #FFF;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
}
.sexybutton:HOVER {
  background: #BEBEBE;
  background: -moz-linear-gradient(top, #DDD, #666);
  background: -webkit-gradient(linear, left top, left bottom, from(#DDD), to(#666));
  border: 1px solid #B6B6B6;
  color: #444;
  filter: progid:DXImageTransform.Microsoft.Gradient(StartColorStr='#DDDDDD', EndColorStr='#666666');
  text-shadow: 0 1px 0 #DDD;
}

Summary

I’m absolutely convinced that using CSS gradients is now viable. Gradients do make a difference, when used well, to the aesthetic of a webpage – more so, in my opinion, than a few pixels of rounded corner.

I’m also convinced that as we put more and more JavaScript onto our pages the performance hit of making a design work perfectly in all browsers gets less and less preference. We need to start leveraging CSS effects wherever possible; it is not fair to a user to have to wait for 100k of gradient images (and the extra HTML required) for something that can be represented by much less CSS.

I love this way of rendering gradients and will definitely be using it in my future work.

Some links


About this entry