CodeinWP CodeinWP

CSS3 Linear Gradient Syntax Breakdown

This is not going to be an extensive post, but just something to serve as a quick reference, along with some interesting points from the spec.

In another post, I’ll break down CSS3 radial gradients, but for now I’ll just focus on linear, to keep things simple.

The Bare Minimum for All Supporting Browsers

To get a linear gradient to work in all supporting browsers, this is how you do it:

.element {
  background: -moz-linear-gradient(black, white); /* FF 3.6+ */
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #000000), color-stop(100%, #ffffff)); /* Safari 4+, Chrome 2+ */
  background: -webkit-linear-gradient(black, white); /* Safari 5.1+, Chrome 10+ */
  background: -o-linear-gradient(black, white); /* Opera 11.10 */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#000000', endColorstr='#ffffff'); /* IE6 & IE7 */
  -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr='#000000', endColorstr='#ffffff')"; /* IE8+ */
  background: linear-gradient(black, white); /* the standard */
}

Which will produce the following gradient:

I’ve included the IE filter syntax, for those who find this page through a search, and need it, but this post isn’t really about that, so I won’t discuss it.

Couple of things to note about the ‘bare minimum’ code above: First, all I’ve declared are two colors — the start and end of the gradient. That’s all you need for a simple linear gradient. Second, to conform to best practices, I’ve listed the standard syntax last. This future-proofs the code, to ensure that the viewing browser will always be displaying the page based on the standard implementation.

Finally, I’ve also included the old syntax for WebKit-based browsers, as well as the updated version. I won’t be talking about the old syntax here, but do realize that it should be included for full compatibility.

The Full Syntax Simplified

Here’s the same example, but with the full syntax (and without all the proprietary stuff), so we can break it down:

.element {
  background: linear-gradient(top, black 0%, white 100%);
}

The above code (with all the necessary proprietary prefixes) will produce the exact same result as the simple ‘black, white’ example from above. Let’s see what each part does.

The Gradient Angle or Starting Point

Where you see the word “top”, you have one of two options: You can declare the angle that the gradient will take, or you can tell it where to start. In this example, we tell it to start at the top, which would be equivalent to an angle of “-90deg”. So this would produce the same result:

.element {
  background: linear-gradient(-90deg, black 0%, white 100%);
}

You would also get the same result displayed if you used an angle of “270deg”, which is equivalent to “-90deg”.

So you can use one of the positional keywords (top, right, left, bottom) or else just give it a specific angle numerically, and it will figure out where to start.

Update (Oct. 27/2011) The syntax for the angle value has changed in the spec, and this has been implemented by Mozilla. I will be posting more details here when I understand it better and have time to experiment, but it might be a while since I don’t think any stable version of Firefox uses the updated syntax.

The Color Stops and Positions

With a simple linear gradient, you just need two color stops, without specifying positions (as shown in my first code example). But in my extended example, you’ll notice I’ve included the position of each color, in percentage values.

This tells the browser where the full version of the color will begin (not where the gradient gradually starts to fade). The browser will naturally figure out the actual gradient; you just have to tell it where the “gradual change” should completely “stop”. In the example above, the “gradual change” stops right at the bottom of the element, so you don’t really see much (if any) full white in that element.

If we changed the value to 50% for the white “stop”, the result would look like this:

So the “white” now “stops” at 50%, and the rest is solid white.

Adding Color Stops

To add color stops is nothing overly complicated; just add as many comma-separated values as you want. Here’s the CSS for a rainbow:

.element {
  background: linear-gradient(top, red 0%, orange 15%, yellow 30%, green 45%, blue 60%, indigo 75%, violet 100%);
}

And here’s the result:

Browser Support

All things considered, browser support for linear gradients is pretty good. But more than likely, depending on your target audience, unless you’re using a simple two-color gradient, then potentially around 20-60% of users won’t see the gradient (naturally, because of IE6-8).

Chrome has supported linear gradients since (I believe) version 2. Starting with version 10, Chrome now supports the simplified syntax. The other browser versions that support linear gradients are: Firefox 3.6+, Opera 11.10+, and the upcoming Internet Explorer 10 supports linear gradients using the standard syntax.

Mobile support for linear gradients includes: iOS 3.2+, Opera Mini 5+, Opera Mobile 10+, and Android Browser 2.1+.

As far as I know, no browser supports linear gradients using only the standard syntax.

Some Closing Points

Here are some points of note for linear gradients:

  • CSS3 gradients are not properties; they are images rendered as such by the browser
  • You can use a gradient anywhere you would use url(image.jpg) in your CSS
  • The syntax that creates the gradient is actually a function that takes the various values as arguments; see how the spec explains it
  • You can also specify a repeating linear gradient, which could come in handy in certain cases
  • The percentage values for the color stop positions can also be expressed in pixels
  • For the color stops, negative percentage values (e.g. -20%) and percentages higher than 100% are perfectly valid

Anything else about linear gradients that I’ve missed here? Let me know in the comments and I’ll add it.

38 Responses

  1. SAiNT says:

    lol, i was just looking for gradient properties a few minutes ago, and here you go… :-)

    > As far as I know, no browser supports
    > linear gradients using only the standard syntax
    – that’s sucks :-(

    btw, is it safe to use “background: linear-gradient” as “future proof”?

    to those, who seek more information on Gradients:
    this really helped me:

    http://www.webkit.org/blog/1424/css3-gradients/

    • Well, the syntax without the prefix is the future standard, so yes. But as far as using “background”, that’s just for brevity. To be honest, it’s probably better (depending on your code habits) to use “background-image” instead.

  2. Sumair says:

    why vendor specific properties

    its so hard to remember all of them

    when css3 going to finalize?

    • SAiNT says:

      actually, they are not so different if you want a simple gradient.
      try to pick yourself a gradient based on updated webkit syntax and then add -moz prefix..

  3. J. Hendrix says:

    Thanks for the tutorial!

  4. Craig Patik says:

    If you’re using a simple 2-color gradient like these example, you can make the Webkit syntax a little easier by using from and to instead of color-stop:

    
    background: -webkit-gradient(linear, left top, left bottom, from(#000000), to(#ffffff));
    

    Also, in 2011 I don’t think it’s necessary to include both Webkit syntaxes unless you’re writing code that you may not touch for years. Chrome will continue to support the old syntax for some time, probably until Safari 5 usage drops off a lot. (Safari doesn’t support the new syntax yet.)

  5. Beben Koben says:

    hmmm…like this basic process gradient…nice nice
    here tools generator CSS Gradient Tools
    xixixixiii :)

  6. Rey says:

    Great list with cross-browser support. Although I don’t understand why it is background: -moz-linear-gradient:; and not just: -moz-linear-gradient:; or even background-linear-gradient:;, would be easier to seperate them appart.

    Thanks for the list will add them to cssprops!

  7. John says:

    Great Post. Has anyone had any issues with gradients in the android browser or iphone browser? The phone does the gradient correct at first and then when you scroll it takes a long time — if it ever does — to render the gradient again. Is there a work around?

    • I’ve never heard of that bug, and I don’t own an android device to test it.

      But I am curious, and would like to have a way to test stuff on Android browser, so I’ve decided to try to run an Android browser emulator, as per these instructions.

  8. Adam Brons says:

    I’ve tired the following code based on your example above on Android Emulator using version 2.3 and it does not work. I’ve got it working in all other browsers without issue, but Android. I’ve not tried iPhone yet, but I’m really hoping to get it to work on Android as well.

    .myClass {
    background-image: -moz-linear-gradient(top, #939598, #6d6e71); /* FF 3.6+ */
    background-image: -ms-linear-gradient(top, #939598, #6d6e71); /* IE10 */
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #939598), color-stop(100%, #6d6e71)); /* Safari 4+, Chrome 2+ */
    background-image: -webkit-linear-gradient(top, #939598, #6d6e71); /* Safari 5.1+, Chrome 10+ */
    background-image: -o-linear-gradient(top, #939598, #6d6e71); /* Opera 11.10 */
    background-image: linear-gradient(top, #939598, #6d6e71); /* the standard */
    background-color: #FFFFFF;
    }

    • Andrew says:

      I know this is very old, but I thought I’d chime in in case anyone stumbled across this looking for information. I wasted time troubleshooting this, no need for anyone else to.

      background-image: -webkit-gradient(linear… will give trouble. I had to modify to use shorthand background method.

      background: -webkit-gradient(l… finally got it working. Only had issues in testing on my ancient 2.2 Froyo or whatever snack that release was named after

  9. Paul says:

    Hey, what a great post!

    Thank you so much, I’ve finally got my button gradient (and hover) working across all browsers :)

    I must say that it is a lot of effort and code for a simple gradient that a 1px image repeated would have achieved a lot quicker. Personally, I think I’ve used CSS because its ‘there’ but in my case not at all necessary.

  10. Karen Menezes says:

    you guys should check out the online gradient generator on colorzilla. http://www.colorzilla.com/gradient-editor/
    amazing! adds a fallback for old browsers, filter for IE, and vendor prefix for the rest.. also includes old syntax for the older webkit browsers..
    i don’t think it does radial, though…

  11. Guillaume says:

    Thanks for the post.

    Some related questions:

    1/ Any ideas why in IE gradients overflow rounded borders? Is there any way to bypass this issue?
    2/ How could we prevent CSS errors due to the use of vendor prefixes (error in parsing value)? Quite annoying.

    • Hey, Guillaume.

      There are some solutions and workarounds to the IE overflow issue:

      http://stackoverflow.com/questions/4692686/ie9-border-radius-and-background-gradient-bleeding

      They’re not the greatest, but it seems the issue can’t really be resolved with just the border-radius property.

      And about your second question:

      Don’t worry about CSS validation. Validation does nothing for your documents other than give them the superficial “this page is valid” green checkmark. Which doesn’t mean anything in practice. Validation is a guide, that’s all.

      And CSS validation should be even less important than HTML validation. Also, you can choose different validation options that will cause the vendor prefixes to be viewed as “warnings” and you can also tell it to recognize valid CSS3 properties:

      http://jigsaw.w3.org/css-validator/#validate_by_uri+with_options

      • dan says:

        Hey, what a great post!

        Thank you so much, I’ve finally got my button gradient (and hover) working across all browsers :)

        I must say that it is a lot of effort and code for a simple gradient that a 1px image repeated would have achieved a lot quicker. Personally, I think I’ve used CSS because its ‘there’ but in my case not at all necessary.

  12. Hopz says:

    Also note for the IE “filter: ” — You cannot shortcut your hexadecimal color values. For example, you can’t do “#FFF” to represent “#FFFFFF”. Otherwise, IE9 will freak out and mess everything up. Weird.

    • Waverider says:

      Thanks for the great outline.
      I am finding that the code:

      filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=’#000000′, endColorstr=’#ffffff’, GradientType=1); /* IE6 & IE7 */
      -ms-filter: “progid:DXImageTransform.Microsoft.gradient(startColorstr=’#000000′, endColorstr=’#ffffff’, GradientType=1)”; /* IE8+ */

      does not fill the screen with a linear gradient in IE9 – it leaves the bottom section of the screen in the plain background color specified for non-supporting browsers.
      Is there any way of overcoming this?

  13. Adam Pery says:

    See nice custom menu line-gradient example here:
    http://www.xhtml.co.il/en/Tools/Linear-Gradients-Custom-Menu
    It is really helpful

  14. Tranhoa says:

    amazing! adds a fallback for old browsers, filter for IE, and vendor prefix for the rest.. also includes old syntax for the older webkit browsers..
    i don’t think it does radial, though…

  15. Jason says:

    Thank you. Worked like a charm. I tried using http://ie.microsoft.com/testdrive/graphics/cssgradientbackgroundmaker/default.html but that did not work. What is up with the additional “image” name to the end of the mark up?

  16. roman says:

    I like CSS3, unfortunately it’s bad supported by browsers.

  17. Abzoozy says:

    I wanted to use rgba with IE but it doesn’t work out :S dammit
    any workaround??

    I would like to go from transparent to white

  18. Abzoozy says:

    sorry I mean I want to use this rgba(114,0,0,0)

    • Depending on what you’re doing, you can try this:

      http://kimili.com/journal/rgba-hsla-css-generator-for-internet-explorer/

      It’s a tool that lets you plug in your RGBA value and it will convert it to an IE filter. Normally, that tool is good for a solid background that’s sem-transparent, but you can also take the semi-transparent colors and plug them into an IE filter gradient. So your example would look like this for IE6-8:

      
      .element {
          filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#00720000', endColorstr='#FFFFFFFF');
          -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr='#00720000', endColorstr='#ffffffff')"; /* IE8+ */
      }
      

      Notice that the color values now include 8 hex digits. The first two digits represent the alpha setting.

      Hope that helps. Just remember not to over use these filters on a single page, otherwise they will cause the page to slow down.

  19. Abzoozy says:

    found it man!!! never new hexa had #AARRGGBB
    :D now I am happy

    you can use it as #0072000a

  20. Nik Rolls says:

    Just a note — Microsoft have completely dropped vendor prefixes with the latest builds of IE10, so you can remove that requirement. They now support the CSS3 standard 100%.

  21. sandeep says:

    w3.org gives a warning
    Property -webkit-linear-gradient(top,#EAEAEA 0%,#BBB 100%) is an unknown vendor extension
    what is this and how to recover this?

  22. Somesh says:

    I want to create a transparent gradient (starting color to transparent at end) gradually decreasing. Like that i am looking for css code.

  23. Ros says:

    linear-gradient is absolutely beautiful, but I’m gonna wait untill most browsers fully support it. I hate having to write 10 lines of code just for it to work on every browser on the face of the earth, so ugly coding.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).