Quick Tip: Understanding CSS3 Gradients
Tutorial Details
- Technology: CSS3
- Length: 5 Minute Video
- Difficulty: Moderate
Creating an image only for the purpose of displaying a gradient is inflexible, and is quickly becoming a bad practice. Unfortunately, at the time of this writing, they very well might still be required, but hopefully not for much longer. Thanks to Firefox and Safari/Chrome, we can now create powerful gradients with minimal effort. In this video quick tip, we’ll examine some of the differences in syntax when working with the -moz and -webkit vendor prefixes.
Webkit
While Mozilla and Webkit generally adopt the same syntax for CSS3 properties, they unfortunately don’t quite agree when it comes to gradients. Webkit was first to embrace gradients, and uses the following structure:
/* Syntax, taken from: http://webkit.org/blog/175/introducing-css-gradients/ */ -webkit-gradient(<type>, <point> [, <radius>]?, <point> [, <radius>]? [, <stop>]*) /* In practice... */ background: -webkit-gradient(linear, 0 0, 0 100%, from(red), to(blue));
Don’t worry if your eyes gloss over at that syntax; mine did too! Just note that we require a comma-separated list of parameters.
- What type of gradient? (linear)
- X and Y axis coordinates of where to begin. (0 0 – or left-top corner)
- X and Y axis coordinates of where to conclude (0 100% – or left-bottom corner)
- What color to begin with? (from(red))
- What color to conclude with? (to(blue))
Mozilla
Firefox, which implemented gradient support with version 3.6, prefers a slightly different syntax.
/* Syntax, taken from: http://hacks.mozilla.org/2009/11/css-gradients-firefox-36/ */ -moz-linear-gradient( [<point> || <angle>,]? <stop>, <stop> [, <stop>]* ) /* In Practice */ background: -moz-linear-gradient(top, red, blue);
- Note how we’ve placed the type of gradient, linear, within the vendor extension.
- Where should the gradient begin? (top – we could also pass in degrees, as in -45deg)
- What color to start with? (red)
- What color to conclude with? (blue)
Color-Stops
What if you don’t need a 100% gradient from one color to another? This is where color stops come into play. A common design technique is to apply a short and subtle gradient, like this:
In the past, the standard implementation was to create an image, set it as the background of an element, and set it to repeat horizontally. However, with CSS3, this is a cinch.
background: white; /* fallback for older/unsupporting browsers */ background: -moz-linear-gradient(top, #dedede, white 8%); background: -webkit-gradient(linear, 0 0, 0 8%, from(#dedede), to(white)); border-top: 1px solid white;
This time, we set the gradient to conclude at 8%, rather than 100%, which is the default. Note that we’re also applying a border top to add contrast; this is very common.
If we wish to add a third (or Nth) color, we can do:
background: white; /* fallback for older/unsupporting browsers */ background: -moz-linear-gradient(top, #dedede, white 8%, red 20%); background: -webkit-gradient(linear, 0 0, 0 100%, from(#dedede), color-stop(8%, white), color-stop(20%, red);
- With the -moz version, we designate that, at 20% of the element height, we should now be at the color red.
- For -webkit, we use color-stop, and pass in two parameters: where the stop should occur, and what the color should be.
Important Notes About CSS Gradients
- Use them as much as you can. If it’s okay to let IE users see a solid color, I encourage you to use this method.
- IE6/7/8, Opera, Safari 3, and Firefox 3 cannot render CSS3 gradients. Firefox and Safari users generally upgrade often, so that’s not as big of a deal.
- Always apply a default, solid color, background for browsers that won’t understand the vendor prefixes.
- Never use a red to blue gradient, as I did for the examples.
- Webpages don’t need to look the same in every browser!
Thanks for reading/watching!








jQuery Lightbox Evolution only $12.00
Events Calendar Pro - Wordpr ... only $30.00 
Hey never been the first neato!
Heh, thanks Jeffrey I watched you do the gradients in the bubble menu tutorial but this totally cleared it up and now makes sense!
As always, keep up the great helpful stuff, thanks!
-Ryan
Hey Jeff, we ever gonna see the source code from that pure-css header you posted on the tumblr a while ago?
Haha. You saw that? Yeah, I just need to clean it up. Maybe later this week?
Sounds great, that’s some serious css-ninja…ness. Moreover, I think it’s a great example of the power of CSS3 and it’s problem-solving awesomeness.
Hey a week ago or more i saw that too!
Great quick tip!
Just one question, when I use a gradient on the body tag, it repeats every 7px or so (http://drp.ly/Fbt2R) does anyone know whats wrong?
It’s because, with nothing on the page, the body element doesn’t take up any space…other than the default styling that your browsers adds to the body element.
Thanks (I should have known that… haven’t been doing much CSS lately), is there a way to get the gradient not to repeat just go from top to bottom?
@nanochrome
If you want to overlay thw whole site you can create on the top, the first element after a “div#overlay” and give some css:
width:100%;
height:100%;
position:absolute;
maybe z-index:9999
and add the gradient.
Just set height: 100% to the html element, and apply it that way.
html {
background:-moz-linear-gradient(top, red, green);
height: 100%;
}
..the first element after “body” (wp is deleting html tags in comments? o.O )
Just when I was starting to like red to blue too.
I seen a tip today about always putting the CSS standard last.
For example
-moz-box radius: 10px;
-webkit-box-radius; 10px;
box-radius:10px;
Would that follow with the default solid color? Would the best practice be to always run that after the proprietary css code for gradients?
Thanks Jeff.
seeing more and more CSS3 Gradients article these days.
Can they only go vertical or can they be used horizontally as well?
They can go any direction. -moz-linear-gradient(45deg, red, green);
Is there any way to get a “progressive enhancement” spin on this technique? Would like to keep my design consistent by letting IE get to the images while letting modern browsers get css3 gradients.
You can use conditional comments to test for IE, and then simply serve a background image (gradient) instead. Or, if you’re feeling nasty, you can target IE8 and below directly in your stylesheet with:
body {
background: url(path/to/image.jpg) repeat-x\9;
}
Note the \9.
Be careful with this. Better to use conditional statements…but it’s good to know nonetheless.
You can also use a Javascript based utility called Modernizr that detects browser compatibilities.
http://www.modernizr.com/
I prefer using this method as opposed to browser-specific hacks, because you can implement new CSS3 techniques based the support of such features. Then, you can easily do elaborate fallbacks for browsers which do not support the specific CSS3 feature.
Jeffery, I always love your tutorials. While this is indeed cool, the whole IE thing is an issue….if I have to do an image anyway….and i have limited time, I’m going with the image on all until its supported in all. I of course am speaking of things I have to do for work. On my own stuff where i have more time to do flexible stuff, then of course I like to use this stuff.
P.S. Jeffery….any chance you posting the code to make that lavalamp nav move the ’selected id depending on what you click. So if I have it as an include on 5 pages, how do I move that id to the correct li position?
Hey Jeremy – Yeah, for some projects it may not make sense. But for personal websites and such, I’d absolutely use them.
You wouldn’t use JavaScript for that lavalamp tut. PHP would determine the page, and apply the class of selected accordingly. For example, WordPress adds a class of current_page_item to the current page. Are you using a CMS?
Yes indeed…WordPress
Yeah – in that case, change the class from “selected” to “current_page_item.”
Gradients are not CSS3 it’s not in the suggested spec..
Great tutorial!
P.S. I heard today about this InType and it is awesome.
Nice one as always! Thanks!
Hi Jeffrey!
Actually there is a way IE (6-8) will do gradients too!
Not as good as the new CSS3-gradients, but at least..
/* for IE 5.5 – 7 */
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=1, startColorstr=red, endColorstr=blue);
/* for IE 8 */
-ms-filter: “progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=red, endColorstr=blue)”;
The GradientType is either 0, which means from left to right or 1, top to bottom.
I don’t think there are such things like a colorstop, but for simple gradients from grey to black this will do it!
And hey Jeffrey, keep going! I really like your screencasts!
Hey Gerard,
Yeah, you’re right! But as I understand things, it’s not nearly as flexible, and is probably better not to use them. But I could be wrong.
Yeah, thats true, unfortunately they can only do only transitions from one color to another..
But hey, better than have to make separate images for this crappy little IE browser
I think this (indeed inflexible compared to the awesome CSS3-enhancements) filter would also solve the problem Jeremy Carlson mentioned a few comments above.
In my next project which relies on some kind of (simple) gradient, I’ll give the CSS3/MS-Filter styles a try ^^
This is another great article highlighting the importance and development of CSS 3. With its impending release as a standard, and the coming release of IE9 (which will support CSS 3) it seems this technology will soon start having widespread usage.
Being able to do simple tasks as gradients with CSS rather than using images will be a huge advantage for web designers, as it will allow the same gradient swatch to be applied again and again in multiple DIVs, instead of creating separate background images of gradients.
I look forward to reading more about CSS 3 and its technologies. A tutorial covering exactly what can be achieved in each browser with CSS 3 and when each will support it would be very useful.
Thanks for the article guys, learned alot
This looks interesting : http://css3please.com/ although for ie you’ll have to keep your gradients simple.
Can not wait until CSS3 is past rough draft stage in w3.
Nice tip there.
Oh and by the way: http://dowebsitesneedtolookexactlythesameineverybrowser.com/
Jeff, I see you like rasta colors) Also wanted to ask will there be a tutorial for example about, if I have one picture which contains over 10 smaller pictures, how is it possible to display only one for example.
Or maybe some tuts about a variety of layouts?
CSS sprites, there are articles here in Nettuts for that.
Right – You create a sprite, and then set the image as a background of your element. Next, you set a width and height to the element to only display your desired portion of the background image.
Wow. Thnx for feedback guys.
very useful and great explanation. thanks for share
I was recently working with these gradient definitions on a project that was applying a gradient at the top of a div to apply a shadow effect for the element above this div, as is shown above. However, this div element is not set to a fixed height as it contains variable amounts of text in various instances. I wanted the shadow to show with a fixed throw distance in any case, rather than as a percentage of the height of the div element.
In the Webkit definition, color-stops can be defined at fixed points from the starting point, and so can be given a fixed value like 1em. However, I was not able to find an equivalent type of implementation in the Mozilla definition.
I realize that i could have created a fixed height div to handle this shadow, and then wrapped it with the variable height div, but this seems unnecessarily complex and ugly (This is the solution I eventually came to). Am I missing something, or is there really no way for the Mozilla gradient to define a fixed point for a color-stop rather than a possible variable percentage of the element’s height?
I’m a-loving CSS3! It’s sooo NICE!
It would be nice to see a HTML prototype focusing on CSS3′s image and color improvements, like multiple backgrounds, gradients, resized backgrounds etc
Nice overview! Now you need to do a Quick Tip for understand Gradients on Canvas. Those are a b*
Woow
That’s very useful
Thanks..!
Thanks for the tip, I enjoy these.
Youtube is acting like crap right now…I kind of liked the quality and service of the other ones you have used in the past.
“Webpages don’t need to look the same in every browser!”
Explain that to the client.
Is this valid CSS?
“Valid” is a very fluid term in regards to CSS3 in modern web design / development.
If you tried to validate Jeffrey’s code in W3C’s CSS3 Validator, it will show a bunch of parsing errors. This is due to the nature of CSS3 implementation at the moment, and mainly because of the vendor prefixes required to create CSS3 gradients.
Now on the flip side, Jeffrey has used correct and “valid” syntax according to the browser vendors for these gradients. The fact that W3C has yet to finalize the CSS3 specifications means until then we will not have a concrete answer as to what is valid or invalid when it comes to CSS3.
All we can do right now is follow progressive enhancement techniques, and pay attention to the browser vendors for direction and proper implementation of CSS3.
Thanks for this great tip and explanation Jeff. I’ve only just started delving into the world of CSS3 because of building a new site and I’m amazed at how easy and brilliant it is. Can’t wait to see more
Is there a method of having the second colour as transparent?
Any of the colors can be transparent, you simply have to use the a RGBA syntax as the color.
Example:
If you wanted the second color to be Black at 50% opacity, the RGBA color would look like so:
rgba (0,0,0,0.5)
More information here:
http://www.css3.info/introduction-opacity-rgba/
Great, clear, concise explanation of linear gradients with CSS! Thanks for sharing!
Thanks for the tutorial! Im here are school which are strictly PC’s running IE so when I get home to my Mac I will try this for sure.
Great quick tip, Jeff.
nive tut
lol @ “Never use a red to blue gradient, as I did for the examples.”
Nice post, I haven’t had a chance to use CSS3 gradient yet. I’m sure this will help.
Thanks.
This post is exactly what a newbie like me needs. Thanks for the knowledge.
I have one question though: is it possible to apply gradients on borders?
Just recently I’ve been upgrading some of my old websites to make use of the cool CSS3 effects available, and get rid of some of the images I’ve been using for rounded corners and background gradients.
One of the issues I just ran into today was the fact that when you have a page that doesn’t extend below the browser window and you want a Gradient on the body, it will simply repeat the gradient per the size of the content.
So I found a solution that at least looks good in this situation. You will get the gradient for the full length of your content area, then it will simply show the background color you setup (normally the final color of your gradient)
html { background: #cbccc8;}
body {
background-repeat: no-repeat;
background: #cbccc8;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbccc8));
background: -moz-linear-gradient(top, #fff, #cbccc8);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=’#ffffff’, endColorstr=’#cbccc8′); }
So I set the background so that it doesn’t repeat on the body, that way you don’t see that annoying effect, then simply set the background color on the HTML to be the last color of my gradient (#cbccc8).
Hopefully this helps other people trying to find a solution to this issue.
Have always used background images from a psd up until now, so this process really speeds things up for me.
However, I would like to know the best practise for keeping the white line specified in border top but then have a outer border around both the white line and the gradient. Any suggestions ?