A Farewell to CSS3 Gradients

Before we get started, let’s get one thing straight:

I ♥ CSS3.

I understand that we’ve never had it so good. In fact, I have no doubt that time-travellers visiting from 2004 would be sick with jealousy at how easily we now conjure up rounded corners, shadows, and object rotations.

Sure, the browser-specific prefixes (i.e. -moz, -webkit -o, etc) are an irritation, but happily the rest of the notation is sensible, consistent and reliably supported across modern browsers.

That is, with one notable exception…

CSS3 gradients: Yes, they’re actually kinda crappy.

While the idea of programmable gradients is great, using them is seriously messy. Even in perfect-browser-utopia, gradients are consciously limited to rudimentary linear or radial application. You certainly can’t combine them, or make them contour a shape or anything useful like that.

More importantly, support is complicated in most browsers and non-existent in some.

Here’s a snapshot of the current state of play:

Browser Radial CSS Linear CSS
Firefox -moz-radial-gradient( 500px 25%, circle, blue 20px, #eef 40px ); -moz-linear-gradient(top, #444444, #999999);)
Chrome 11, Safari 5 -webkit-radial-gradient(#cde6f9, #81a8cb); -webkit-linear-gradient(top, #444444, #999999);)
Chrome -webkit-gradient( radial, 500 25%, 20, 500 25%, 40, from(blue), to(#eef) ); -webkit-gradient(linear, left top, left bottom, from(#444444), to(#999999));
Opera 11 No support -o-linear-gradient(top, #444444, #999999);)
Opera 10- No support No support
IE10 beta -ms-radial-gradient(top center, circle cover,
orange, yellow 25px, turquoise)
-ms-linear-gradient(30deg, orange, yellow 50%, turquoise);
IE9 No support No support
IE8 No support -ms-filter: "progid:DXImageTransform.Microsoft.gradient( la la la...
IE5-7 No support filter: progid:DXImageTransform.Microsoft.gradient(la la la..

Wow, that looks fun, huh? In short, it’s a blunt instrument with cranky syntax and patchy support.

Ok, so what’s the alternative?

While there have been some great recent discussions on the subject of gradients — John Allsop’s recent article gives the perfect overview — most focus on using CSS3, while occasionally patching a hole here and there with dab of SVG.

Could it be we’re looking at it the wrong way?

In 2011, SVG is actually well-supported by all the current mainstream browsers — even on mobile. What if we started with SVG and patched around the edges? Looking back over the 15 year evolution of CSS, it’s been a slow, often tortured development. At that development rate, it’s hard to imagine CSS ever developing into a truly powerful, flexible, visual design tool.

But with SVG, arguably we have that fully-featured, visual language today.

Step back: Exactly what is SVG?

So, if you’re thinking ‘SVG? That’s the new Volkswagon, right?‘, let’s do a quick catchup.

Scalable Vector Graphics (SVG) is an XML-based file format for describing two-dimensional vector graphics. Like Illustrator’s AI format, it builds images using maths and geometry, rather than a grid of pixels (i.e. JPEGs, PSD, etc). That gives SVG images some very web-relevant superpowers — chiefly, SVG scales without distortion while maintaining tiny file sizes.

How do you make SVG?

There are quite a few ways to make your own SVG.

  • Hand code: If you’re geeky enough, just open your ol’ text editor and start typing. Like most XML formats, SVG mostly makes sense when you read it.
  • Illustrator: Adobe Illustrator can export to SVG, though to be frank, the code is not exactly svelte and sexy. Maybe not the right tool here.
  • Inkscape: Inkscape is a powerful free, open source editor that uses SVG as it’s native file format. It rightly has lots of fans, but might be overkill for producing simple web-ready graphics.
  • Raven: Aviary’s Raven is an online vector application that includes a ‘save to SVG’ option. Raven is Flash-based, but it’s otherwise free and writes quite decent code too.
  • SVG Edit: My personal favorite, Google’sPavol Rusnak’s SVG Edit (hosted on Google Code)

That last one might be a surprise as Google Code isn’t exactly the first place you think when it comes to visual design tools. As yes, it’s as ugly as a bulldog eating porridge. But happily there’s also a lot to like about it:

  1. It’s free, and we always like free.
  2. It’s built from plain ol’ JavaScript, HTML, CSS and SVG so you can either use Google’s online version or run a copy on your local system.
  3. It writes tight, clean, readable markup.
  4. SVG Edit is designed to keep you in close contact with the SVG code all the way through the process.

That last point is important. As front-end designers, we tend to naturally distrust WYSIWYG tools that hide the code away from us. Indeed, most of us take pride in hand-coding our hex colors, font stacks, line-height settings and base line rhythms. Hell, some of us even choose our t-shirts color based on their RGB values (no pointing). SVG Edit encourages you to ‘get up close and personal’ with your SVG in the same way. That’s going to become increasingly useful the more you work with SVG.

That’s enough theory. Let’s run through the simplest of SVG examples.

Example 1: Simple linear gradients

1. Open SVG Edit in your browser (from the link the Demos section).

The blank SVG Edit

The blank SVG Edit Application

2. Before we do anything, try clicking that rather hideous ‘SVG’ button at the top left. A popup showing your blank SVG document will appear. You’ll notice the document size is set to 640px by 480px.Try changing the width to 480px and hit ‘Apply Changes’ to see your changes back in the Visual Editor view.

Nice. You just wrote some SVG.

3. Next select the rectangle tool from the left toolbar and drag out a box roughly the same size as your document. Your rectangle will likely have a stroke outline by default. At the bottom of your editor you’ll notice your fill and stroke controls. Delete the stroke by setting your stroke-width to 0px.

4. Switching back to the SVG code view, you’ll see atag has been added with a set of properties for color, stroke and size. The great thing about SVG is it’s generally very human-readable. Since we got rid of the stroke, you can delete the stroke-width and stroke color properties if you like. If your rectangle doesn’t quite fit your canvas, manually edit the width and height to match the document. It should look something like this:

<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
  <!-- Created with SVG-edit - http://svg-edit.googlecode.com/ -->
 <g> <title>Layer 1</title>
   <rect fill="#ff0000" x="0" y="0" height="480" width="640" id="svg_1"/>
 </g>
</svg>

5. Cross back to Visual Editor view. With your new rectangle selected, click on the Fill color chip (near the bucket). A tabbed popup launches which lets you choose between solid color, linear and radial gradients. Let’s face it: solid SVG color is less useful than plain ol’ CSS here, but the other two tabs are very useful.

Try the linear gradient panel. You can choose your starting and ending colors with the color picker. The ‘x’ and ‘y’ settings control the direction of your gradient. The top-left corner is position 0:0 and the bottom-right corner is 1:1, so a begin-stop of 0:0 and an end-stop of 1:1 will give you a top-left to bottom-right diagonal gradient.

Changing your end stop to 0:1 will switch your gradient from horizontal to vertical. You’ll notice there is a slider along the bottom that lets you control the opacity of the entire object. Alternatively, you can set different transparency levels for each stop with the color picker. Try picking a starting and ending color and then have a peek at the SVG. It should look something like this.

<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
 <!-- Created with SVG-edit - http://svg-edit.googlecode.com/ -->
 <defs>
  <linearGradient y2="1" x2="1" y1="0" x1="0" id="svg_2">
   <stop stop-color="#ff0000" offset="0"/>
   <stop stop-color="#ffff00" offset="1"/>
  </linearGradient>
 </defs>
 <g>
  <title>Layer 1</title>
  <rect id="svg_1" height="480" width="640" y="0" x="0"  fill="url(#svg_2)"/>
 </g>
</svg>

That markup should feel familiar. You’ll see that the gradient is defined at the top between the tags and has a unique ID — “svg_2″. The stops denote our starting and ending colors. Below that you’ll see the tag that is referencing the gradient via it’s ID (id=”svg_2″).

Let’s throw it at a browser.

Open the SVG code view, select the markup and copy it to your clipboard. Next open your favorite code editor, create a new document and paste your SVG in.

Save your document as ‘gradient.svg‘ to a testing folder. Next create a blank HTML document and in the head, add the following code.

<style> html { background: url(gradient.svg); background-size:100% 100%; height:100%; } </style> 

Save the HTML document with your SVG and preview it in a browser. You should be looking at an elegant two color gradient that effortlessly scales to fill ANY current browser window.

But what about three or more color gradients?‘ you say.

Easy. Switch back to ‘gradient.svg‘ in your code editor. You’ll notice the stops in our linear gradient have offsets of 0 and 1 respectively. Add a new with an offset of 0.5 and any color you like, and slot it in between your other two stops like this:

    <stop stop-color="#ff0000" offset="0"/>
   <stop stop-color="#00ff00" offset=".5"/>
   <stop stop-color="#ffff00" offset="1"/>

Save and reload and you should now have a three color rainbow.

Ok, so you might be thinking ‘Fine, but we can do that with CSS3 gradients — what’s the big deal?‘ This is very true, but the SVG does have some nice advantages.

  • Our CSS is so clean you could eat off it.
  • We can tweak and tune our gradient without leaving our code editor.
  • We now have a single set of numbers to manage rather than 4,5 or 6 syntaxes. (Even assuming we still might have to hack for older IE’s)

That’s nice’n’all what about an example that can’t be replicated with a pure CSS solution.

What about Radial Gradients?

SVG Edit - Radial gradient panel

Back to SVG Edit. Select your rectangle again, click on the fill-color chip, and switch to the radial gradient tab. You’ll see a control panel not unlike the linear gradient panel.

By default, gradients are centered on your shape (e.g. position x=0.5, y=0.5) but you’re free to drag and reposition the center point whenever you like.

The outer radius can be adjusted via the radius slider on the right. However I think the really nifty part is being able to have a separate center point and focal point.

Simply uncheck the ‘match center‘ box and position the ‘F’ and ‘C’ icons wherever you like. As you can see in the screencap, this lets you stretch and contort your radial gradient in ways that are reminiscent of spotlights and shadow.

Even the hippest of new browsers can’t do that with pure CSS.

Billy Wilder's 'Sunset Boulevard' 1950 - http://en.wikipedia.org/wiki/Sunset_Boulevard

Great film directors like Billy Wilder and Alfred Hitchcock use light and shadow to tell their story.

Example 2 -Lighting Effects

Recently I watched the old classic Sunset Boulevard and it got me thinking about how brilliantly directors like Billy Wilder and Alfred Hitchcock used shadow and light to create drama. The shadows almost become another character in the story.

seamless-brick tile

Seamless tiles are great but they HAVE to be flat-lit to work

To me, this highlights a natural limitation with seamless tiling bitmaps on the web: By definition they need to be boringly, almost clinically flat-lit.

More precisely, if you want the edges to blend, you can’t make the tile lighter on one side than the other.

What if we were to combine the strengths SVG with tiling bitmaps to get the best of both worlds?

Let’s start with this basic seamless brick tile (left). Rendered by itself, it’s not particularly impressive. Sure, we could use the cicada principle to randomize the brick pattern, but I think it’s the flat, sterile lighting that really makes it dull. Let’s fix that.

Using SVG Edit, I’ve created a simple, midnight blue rectangle with a semi-transparent radial gradient center.

I’ve skewed the focal point toward the top left corner to give it a spotlight feel.

Radial gradients in SVG

Radial gradients in SVG

Copying the code into a new SVG file should look something like this:

<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
 <!-- Created with SVG-edit - http://svg-edit.googlecode.com/ -->
 <defs>
  <radialGradient id="svg_3" cx="0.5" cy="0.5" r="0.5" fx="0.19" fy="0.19">
   <stop offset="0" stop-color="#000000" stop-opacity="0"/>
   <stop offset="1" stop-color="#120747"/>
  </radialGradient>
 </defs>
 <g>
  <title>Layer 1</title>
  <rect fill="url(#svg_3)" x="0" y="0" height="480" width="640" id="svg_1" fill-opacity="0.72"/>
 </g>
</svg>

As you can see, it’s still very concise and easy to read.

Firstly we’ll set up a fallback background for older (mostly IE) browsers that don’t support multiple backgrounds. We’ll also set the height of the HTML element to 100% to ensure our image fills the browser.

html { background:url(bricks3.jpg) ; height:100%; }

Next we’ll add our multi-image background. The brick tile is at the back (last) and our SVG overlays it.

html {
 background:url(bricks3.jpg) ;
  background:url(spotlight.svg), url(bricks3.jpg) ;
height:100%;
}

Note I’m using the shorthand ‘background’ CSS property rather than ‘background-image’ as older IE’s seem to try to read multiple images as one long image when you use the more specific notation. Derp.

Obviously background images will tile by default. That’s perfect for our brick graphic but we want our SVG to conform to the browser window, so we’ll need to specify the background-size like this:

html { background:url(bricks3.jpg) ;
background:url(spotlight.svg), url(bricks3.jpg);
background-size:100% 100%, auto; /* auto is tile */
 height:100%;
}
Hey teacher! Leave them kids alone.

Combining SVG with a simple tile.

Finally we add a dollop of web fonts and a pinch of CSS3 and we get something like this. You can poke at a live example here.

I think there are a number of points worth noting.

The first thing that strikes me is how much impact a very simple SVG can have on a flat-looking tile. The changing light means even tightly-repeating bricks seem far, far less noticeable than they were before.

Secondly, from a technical perspective, you’ll notice that the SVG scales to any browser window instantly and remains crystal clear regardless of screen resolution.

Support for SVG in CSS backgrounds is good in all current mainstream browsers.

  • Chrome (since May 2010)
  • Firefox (March 2011)
  • IE9 (March 2010 beta)
  • Safari (June 2010)
  • Opera (June 2008).

Older browsers will happily render the bricks but not the SVG — for this example, that’s not a bad result. I’m not going to go deeply into workarounds here, but you might consider fallbacks for Firefox 3.6 and IE8 — your call.

Example 3 – Vintage gallery

Use the polygon tool to create a rectangle with slightly bowed-out edges.

Time to get serious and set SVG a bigger challenge. So far our first two examples used just a single rectangle, but — unlike CSS3 gradients — there’s nothing stopping us from combining one, two or more shapes and gradients into a single more complex SVG.

For this last example we’re going to create a loose picture gallery with a vintage feel. The HTML for our gallery is super clean — an unordered list of Flickr images courtesy of the National Library or Ireland. I want to create an auto-resizing SVG frame for each image.

Jumping back into SVG Edit, I’m going to create this new graphic from two simpler shapes.

The first shape is created using the polygon tool. It’s essentially a rectangle with its edges bowed out slightly — almost as if the shape was over-inflated. This shape will be my shadow, so I want to remove the stroke and give it a semi-opaque, 30% black fill.

Happily, SVG also supports a handy set of built-in filters, and we can use one of these to give our shadow a gentle blurred edge.

Select the shape and you should see the blur filter controls appear at the top of the editor. I’ve set my blur to 6 to get the soft edge you see below.

The blur filter

Setting the blur filter to 6 gives us a soft shadow effect.

The second shape is just a rectangle. It has a light gray border and a linear gradient of whites and light grays gives it a glossy ‘photographic paper’ look.

Grab the code from the editor and paste it into a new SVG document. We now have a simple, scalable frame graphic that’s perfect for our needs.

Let’s look at the CSS.

ul li { background: url(polaroid.svg);
 -moz-background-size: 100% 100%;
 background-size: 100% 100%;
 display:inline-block;
 padding:2% 2.5% 3% 2%;
 list-style: none;
  ... }
Photopaper SVG

Using simple SVG to mimic the look of glossy photographic paper

Firstly, we apply our new SVG to the background of the list item, and use background-size to make it match the size for each list-item.

I’m also using display:inline-block on the list-items to make the photos stack across the screen. This generally makes them stack more elegantly than floating each list-item.

We also need to add some padding to make sure the photo doesn’t totally obscure our frame.

The gallery

Our SVG adapts effortlessly to any image regardless of size or orientation.

Finally, I’m using a touch of CSS3 rotation to give the gallery a loose, scattered feel. I’m not going to break down the code for that here, but Frank Fuchs developed this idea in back in May.

Here’s the result.

What do you think?

For me there’s a lot to like about this approach. The strengths of SVG seem clear. Each occurrence of the SVG scales, rotates and reshapes itself without any distortion or loss of image quality. The file size is an order of magnitude smaller — measured in bytes, not kilobytes.

It’s also nice to be able to adjust the blur or opacity with a few lazy keystrokes.

Sure, there are some drawbacks, but not too many.

Currently IE9 supports SVG nicely, but unfortunately not the SVG filters, so our shadow edge appears sharp.

Unsurprisingly, earlier IE’s ignore SVG, but it’s actually their lack of support for the background-size CSS3 property that is the real showstopper here. Scaling SVG is where the real power is. You might be able to concoct an IE8 fallback with Microsoft filters. Good luck with that. Either way, CSS3 gradients certainly aren’t your saviour.

The only other significant non-SVG supporting browser seems to any Firefox before version 4, and with Mozilla’s move to automatic upgrades, this becomes less of an issue every day. Bizarrely, Firefox has actually supported SVG beautifully since 2008 — just not in CSS backgrounds where they’re so useful. Again I say, derp.

Anyway, I hope this article has sparked a few ideas on how you might weave some sexy vectors into your work. If not, it should’ve at least been a good SVG primer.

Bring on the Era of SVG!

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • http://twitter.com/fourandthree Levin Mejia

    Thank you for this post! I wanted to start working with SVG and this definitely gives me the green light to spend some time really perfecting it.

  • http://twitter.com/fourandthree Levin Mejia

    Thank you for this post! I wanted to start working with SVG and this definitely gives me the green light to spend some time really perfecting it.

  • http://www.diigital.com Mike Healy

    I benefit from Pareto’s principal using CSS3 gradients. I get most of what I need done with a pretty small effort.

    They are less powerful than SVG, but usually I only need simple linear gradients with 2-3 colour stops. I can easily duplicate lines in the CSS and alter the prefixes for Webkit, Mozilla, IE10 and W3C support very quickly.

    That’s enough for me for now (with a fallback background image if the gradient is important).

  • http://leaverou.me Lea Verou

    ΙΕ9 does support the filter syntax, even without a prefix. Also, you can combine gradients, with multiple backgrounds.

    • http://twitter.com/alexmwalker Alex Walker

      Hey Lea, on the IE9 filter support: Really? I wonder if it’s a quirk with SVG Edit. Are you seeing a blurred shadow on the polaroid SVG in IE9?
      http://sitepoint.com/examples/svg/polaroid.svg

      • http://leaverou.me Lea Verou

        I’m too lazy to open a vm right now (sorry, it takes ages), but I remember that I used to say in my talks that it needed -ms-filter and then a friend told me it doesn’t. We tested it and it worked.

        • http://twitter.com/alexmwalker Alex Walker

          Interesting. I was mildly surprised when it didn’t work in IE9, but this is what I’m seeing. http://rookery9.aviary.com.s3.amazonaws.com/9832500/9832959_404f_625x625.jpg

          • Phil

            I think Lea was referring to the proprietary CSS ‘filter’ for gradients – IE9 does support it.

    • Jason Johnston

      Unfortunately the filter gradient does not respect border-radius in IE9 which limits its usefulness.

      • http://dan.cx/ Daniel15

        If you also apply the border-radius to a surrounding element and apply overflow: hidden to it, it works as expected. Kinda ugly, but doable if you really want gradients and rounded corners in IE9. Here’s a fiddle demonstrating: http://jsfiddle.net/V8MqC/

  • http://twitter.com/volomike Mike McKee

    I used to use CSS3 gradients until I saw such terrible performance in them. Sometimes I can’t even scroll a page without the page sticking while it tries to redraw the gradient. Also, FF used to have radial radients working great and then I started seeing strange quirks in later versions of FF. So, I went back to using a gradient image, whether repeating image or not.

    • http://twitter.com/alexmwalker Alex Walker

      I’ve found quite a bit of variation between browsers with CSS3 render performance. Large offset box shadows are the thing I’ve noticed can really kill it. 

      I haven’t benchtested it, but SVG feels faster than the equivalent CSS.

  • Dom

    You qualify svg-edit as a Google tool, but while it’s hosted on Google code, I don’t think the project itself is affiliated to Google in any way.

    • http://twitter.com/alexmwalker Alex Walker

      Fair call, Dom. Fixed in the post. Thanks.

      • Dave

        It seems like you did a strikethrough and left a later reference to Google in there. How about actually fixing it properly so the author is attributed unambiguously?

      • Dave

        It seems like you did a strikethrough and left a later reference to Google in there. How about actually fixing it properly so the author is attributed unambiguously?

      • http://stick.gk2.sk/ Pavol Rusnak

        Actually SVG-edit is a community effort so it cannot be attributed just to me. And because it’s license is very liberal (Apache License 2.0), everyone is welcome to join the development!

  • http://madebyeden.co.uk Dan Eden

    I cannot stress enough how much I agree with this. CSS gradients would be great if they _actually_ had a reasonable syntax, but frankly, it’s just ridiculous.

    SVG or even flat images are clearly the way to go, and this article outlines that fact perfectly. Great post!

  • http://www.tyssendesign.com.au John Faulds

    Great write-up Alex and I’m looking forward to when the older IEs drop to small enough numbers where we can start using SVG more widely. I must admit I haven’t done anything with SVG myself, but this is just the sort of primer to kick that into gear.

    It’s worth mentioning though that a lot of the pain with dealing with CSS3 gradient syntax goes away if you use something like LESS or SASS. You set up your mixin right to start with and then it becomes as easy as .gradient(#startColor,#endColor). That’s a simplified example, but you get the idea.

  • http://twitter.com/mickealm Micke Alm

    So what about http-requests? Can the svg’s be sprited?

    • Anonymous

      You should be able to embed them as a data-uri in the CSS, right?

      • http://dan.cx/ Daniel15

        Except the SVGs will probably be bigger than the corresponding CSS3 gradients, and harder to edit as a data URI, so you may as well just use the CSS3 gradients. 

  • http://www.facebook.com/tomelders Thomas Elders

    You should take a look at raphael.js

    http://raphaeljs.com/

    However, I’ve had quite a bit of experience working with SVG in the browser, and I strongly recommend using it sparingly. Performance in mobile browsers is erratic, and sluggish. For gradients, I think images is still the best way to go for the time being. 

  • http://www.facebook.com/tomelders Thomas Elders

    Oh, and on a slightly pedantic note, IE doesn’t support SVG. It’s uses VML, which is similar. IE9 supports SVG, but only partially. 

    • http://twitter.com/alexmwalker Alex Walker

      Thomas, yes when I’m talking about SVG in IE, I’m only talking about IE9. Getting VML to work inside CSS backgrounds.. I’m getting a nervous tick just thinking about it. ;) 

  • http://www.itmitica.com/en IT Mitică

    It would be true if:

    1. I didn’t know the difference between illustration and presentation.

    2. I’m trying to use one tool and one tool only as the single existing solution for all my problems.

    3. I don’t acknowledge that performance issues have always been surpassed.

    Many new CSS capabilities are still rough on the edges, and many of them will not survive on the long term. It’s only logical I need to adapt and diversify accordingly to the current state of technology.

    As general rules though:

    1. I use CSS gradients for simple presentational effects, in healthy amounts.

    2. I use SVG where more elaborate illustrations are needed.

  • http://hynerian.myopenid.com/ Hynerian

    Your browser support table would look a bit less scary on the IE front with CSS3PIE: http://css3pie.com/ Has IE9 support now.

    • AndyW

      Only problem with PIE is that it has all sorts of strange z-index bugs that you have to work around.

      • http://dan.cx/ Daniel15

        That and how slowwwwww it is on complex pages in IE6. It feels even slower than IE7.js (which I am using on my blog)

  • Anonymous

    1) XML ALWAYS solves web problems.
    2) People complain about XML.
    3) Repeat.

  • Guillermo

    Actually, svg is not supported in android.

    http://code.google.com/p/android/issues/detail?id=1376

    • chaux cedric

      Thanks I was wondering too … what a pity

    • http://www.webfadds.com Scott Frangos

      Hi Colleagues — SVG background I placed at my site after reading this excellent tutorial is working fine on my Android browser on the new Toshiba tablet.

  • http://devolute.net devolute

    Great article.

    I’m not sure I’m totally with you on the evils of CSS gradients as (especially for those using a CSS-preprocessor such as Less or Sass) they’re maybe not always as big a pain as you suggest.

    • http://about.me/bradleyjoyce bradleyjoyce

      +1 for sass (and compass)… makes my gradients easy!

    • http://pulse.yahoo.com/_OK5DAACDTIDQWAS5PYVHACSRWE Barbra Barr

      i cant believe this!! me and my sister just got two i-pads for $42.77 each and a $50 amazon card for $9. the stores want to keep this a secret and they dont tell you. 
      Go here, www.tinyurl.com/3qa436v

  • Anonymous

    So you’re complaining about an unstable feature of the CSS3 spec? Of course the syntax is going to be different across browsers. Thankfully, Mozilla has come along and proposed their, much cleaner, gradient syntax.

    SVG, of course, also has a purpose. It’s obviously a lot easier to create SVG graphics with the many editors there are out there. SVG also has a handful of semi-useful filters. Hell, you can even execute JavaScript from within an SVG file.

    However, I’d watch the development of the CSS4 spec once drafts start making it to the public. We’re told to expect a more useful `filter` property in CSS4 that will allow for things like blurring.

    Use the right tool for the job (yadda yadda yadda).

    • Foljs

      So you’re complaining about an unstable feature of the CSS3 spec?
      It’s 2011. It should have been on CSS v1. He rightly complains… Of course the syntax is going to be different across browsers. Everything is “of coursed” if your expectation are low.

      • Anonymous

        You don’t get it. This is a beta implementation. It isn’t meant to be stable. Vendors are giving different implementations a trial. So quit complaining.

        As far as gradients being in CSS1, I’d imagine you weren’t doing much web development back in those days.

  • http://twitter.com/GotNoSugarBaby Jamie Mason

    I’d have called this “Beyond CSS Gradients” to save people thinking this is a call for war between SVG and CSS3. The article’s really more like “I ♥ CSS3, but if you want to combine or contour gradients, you need SVG”.

    Right?

    • http://twitter.com/alexmwalker Alex Walker

      Yes, I’m probably being a *little* cheeky with the title. Just looking around, I see CSS3 gradients everywhere and almost no SVG being used within CSS. Which would be cool if gradients were awesome, so I guess the title is a somewhat clumsy attempt to draw a ‘How so?’ 

      • http://my.opera.com/jax Jonny Axelsson

        Same core functionality for different uses. I would like to see more CSS used in SVG and more SVG used in CSS, even if “just” as background images (IIRC background images could be animated but not interactive, but haven’t checked current stance). 

        So with your examples. Gradient backgrounds are usually of the “rounded corner” category, part of the design, and more likely than not part of a future redesign. These are classic cases for CSS. Your examples, cool btw, are likewise classic cases for SVG, specific graphics for a specific purpose.

        On syntax I am a strong proponent of “keep your markup clean and your style sheet messy”, that is make the markup as descriptive, simple, and minimal as possible, even if that comes at the cost of more complex style sheets, scripts, and other auxiliary files.

  • justintime

    Call me old school but I even dodge css3 unless is some super flashy need for presentation. These techniques are more experimental & fun than actually useful in large scale accords browsers, sure IE sucks but it powers more than 1/2 of the visitors web experience. Use image for gradient and move on…

    • NeuBrew

      I chuckled.

    • http://www.digital-results.com/ Russell Bishop

      Justin – you sir, are a moron.

      • justintime

        First, nick is ‘just in time’ no Justin here.
        Why am I a moron exactly? For having an opinion or having designed sites before you were able to wipe your own a**?

    • http://dan.cx/ Daniel15

      You’ll have to move forward some time, you can’t remain stuck in the past forever. Imagine where we’d be if no website ever innovated, instead just sticking with what everyone else uses.

    • http://twitter.com/baamenabar Agustín Amenabar L.

      I agree with you Mr. Guest, adding PIE would be just anothe messy polifill one has to add to the building a backwards compatible HTML5 site.
      I’ve worked with that and it’s not scalable.
      Rarely I can use LESS so, better stick with practicallity, and simple progressive enhancements, than lousy degradation.

  • http://twitter.com/mkawick Mickey Kawick

    Are you crazy? Look what you can do with CSS3 Gradients. Most of these use some form of gradient.

    http://leaverou.me/css3patterns/

    • http://twitter.com/alexmwalker Alex Walker

      There’s no doubt that Lea’s CSS3 patterns are amazing, but I think that’s more a testament to her wonderful creativity than it is to CSS3’s innate ability to build great backgrounds. She’s almost succeeded despite CSS3’s abilities rather than because of them.

  • http://designedbygold.com Jon Gold

    I use LESS. You can’t possibly argue that I should change from

    #gradient > .vertical( @ orange,@orange2);to

    Layer 1

    • http://twitter.com/alexmwalker Alex Walker

      No. If you were only going to replace linear gradients with SVG, you probably wouldn’t bother. I think it’s the new scope and versatility (as demoed in the later examples) that is the kicker here. 

      On Less and Sass: They are fantastic, but have their own drawbacks. If you control your server it’s easy, but not every front-end dev has access/ permissions to do that on every project.

  • Matt Vaughan

    I agree with others that using the various syntaxes (vendor-specific CSS3 + MS filter) is OK if using a CSS preprocessor, but it leaves IE9 as the main gaping hole requiring a different approach, if it truly doesn’t support either.  (I have seen conflicting reports on its support for filters, but am willing to believe that due to bugs in how it interacts with CSS – for instance, drawing the -ms-filter gradient overlaid as a rectangular element on top of the rounded corners, destroying the latter effect – that maybe they disabled it entirely for release.)

    A StackOverflow user called naeve presents a nice technique for generating the needed svgs for simple linear gradients with a very simple php file that is passed the start and end values (which can be set in the css). See his comment here: http://stackoverflow.com/questions/3934693/gradients-in-internet-explorer-9/5927470#5927470Obviously the technique could be extended for more flexibility by specifying orientation, stops, etc. 

    • http://www.tyssendesign.com.au John Faulds

      There’s no gap in IE9 (or earlier versions of IE either) if you use http://css3pie.com/

      • Dan Smith

        I agree. In fact I dropped my PHP SVG generator workaround for IE9 when PIE 1.0beta5 was released. It can be buggy, but it is a beta product. Sass is also great here but way too slow for development on Windows.

  • Salman Abbas

    And I have to create 3 of these most the time (initial, hover and active)? No thanks. LESS + Preboot = FTW

  • http://twitter.com/gkatsanos George Katsanos

    I agree that the syntax complexity & the browser inconsistencies are leading this module to the trashbin… On the other hand, complicated syntax is unavoidable as the language evolves and new things are added. I guess the problem here is the fundamental flaws of CSS as a ”programming” language. (http://www.gplus.gr/blog/index.php/2011/09/semantic-markup-css-and-crockford/) We’ll see. 

  • Robocat

    Most Android phones do not support SVG (intentional disabling of feature – see issue http://code.google.com/p/android/issues/detail?id=1376).

  • Anonymous

    I don’t get your point. You rather do all that svg stuff than writing a couple of lines of code to get a simple plain gradient?

    And +1 to devolute! SASS rules!

  • http://my.opera.com/jax Jonny Axelsson

    Styled as a “Farewell to…” I don’t think this makes much sense. I have long argued for better integration of SVG, CSS, JS, and HTML http://my.opera.com/jax/blog/svg-2-1-foreshadow-support but the role of SVG and CSS are different, SVG is a markup language for making graphics, including interactive graphics, while CSS enhances existing markup. In the role CSS3 Gradients is intended for, background gradients, it would make sense to use CSS, using one style sheet the boxes would have a gradient, in another they would not.

    By comparison a gradient in an SVG graphic would be an integral part of that graphic. You *can* use it for similar purpose, assuming the browser supports CSS, SVG, and the integration between them, by adding a gradient SVG as a background image with CSS. Web designers have done much worse, but it is still not as convenient.

    And the syntax is not so bad. CSS, having been around for longer, has had some good thoughts about future compatibility, and the browser prefix is one of those. If there hadn’t been different syntax for different browsers, these early attempts at introducting a feature would cause problems further ahead when the feature is standardised (and -prefix- features slowly dropped). Early SVG has on the other hand introduced future-hostile restrictions, which hopefully the working group is getting rid of.

    We should focus on functionality, not syntax. Ideally CSS gradients should be as SVG compatible as possible, so that a program that already has implemented SVG could easily implement CSS gradients, and that the way gradients behave in CSS mirror the way they behave in SVG, making it easier to learn and use CSS and SVG.

  • http://www.facebook.com/profile.php?id=688155723 John ‘Avant’ Gardner

    SVG isn’t always appropriate. For pages that use a lot of gradients, it’s going to wind up adding the same overhead and HTTP requests as if you’d used PNGs in the first place. The only added advantage SVGs offer is that handy scalability; but that’s not going to be useful for tiled images.

    I’d say that CSS3 gradients and SVG gradients both have their places, depending on your approach. If you wanted to add a vignette or spotlight, SVG is by all means the ideal choice. For shaded backgrounds, however, CSS3 gradients are the better alternative (if you can get past the number of vendor prefixes needed; but those will drop off over the years).

  • http://twitter.com/Fyrd Alexis Deveria

    Great to see an article remind people of the power of SVG! SVG-edit has actually been a community effort, with the bulk of the work being by Pavol, Jeff Schiller and myself. Sadly we’ve all been too busy with other things to work on it lately, looking for contributors to take over.

    For gradients I would actually recommend the largely stable 2.6 builds, as they include options to add multiple stops, elliptical gradients and other spread methods.

  • http://twitter.com/sbussard Stephen Bussard

    This is a pretty good approach and you’re definitely thinking outside of the box, but I use less to generate gradients for me on the fly. Generating SVG on the fly adds another level of complexity.

  • Anonymous

    Not sure that I would want to maintain that XML syntax. sass/compass is definitely the way of the future.

    • http://twitter.com/superstructor superstructor

      +1 that while the features of SVG are useful, XML syntax sucks badly.

      Frameworks such as github.com/visionmedia/nib/pulls output SVG automatically from CSS gradient definitions making SVG usable. 

  • Eyesea

    I’ve been waiting ten years for consistent browser support for SVG. It looks like I’ll continue to wait. Glad to know I am not the only one longing for this.
    I do think some of the new CSS features are being a bit overdone right now.

  • http://twitter.com/superstructor superstructor

    Interesting article with a lot of useful information.

    Compass+SASS or Stylus+Nib both provide stylesheet pre-processors that will generate all browser prefixes and equivalent SVG from a single gradient definition.

    Its simply incorrect that you cannot combine gradients, here are some examples of complex layered CSS3 gradient patterns right here http://css3patterns.com/

  • http://twitter.com/potterandweb POTTER & WEB

    I like this, will be using this editor a lot more in the future, can see many advantages of this method.

  • http://twitter.com/potterandweb POTTER & WEB

    I like this, will be using this editor a lot more in the future, can see many advantages of this method.

  • Elliot Birch

    Alex, another amazing article from you! I remember talking to you about this a few months ago and you convinced me back then. But this article is awesome! Keep it up.

  • http://twitter.com/mhisWebDesign Marc Haunschild

    You gave some great examples here – for a more trivial use, css gradients are really useful. Sure, writing them is no fun – so let a tool do it for you:

  • Terry

    Have you tried vector icons and/or vector logos the same way? Would be nice to change the color of vector icons on the fly. Maybe even add drop-shadow etc.

  • http://twitter.com/thezenmonkey Richard Rudy

    I do have to take issue with your point that you can’t combine gradients. Using rbga and the new css3 background properties it is possible to combine multiple gradients. I’ve been using it to create beveled buttons for months

  • Phil Birnie

    Thanks for the post, Alex.  Agree with others that we have to use the right tool for the job, but it’s nice to have this in our hip pocket.  Just as an FYI to anyone who has this issue, the filters do not appear in Safari 5.x nor are they present in SVG Edit… 

  • Phil Birnie

    Thanks for the post, Alex.  Agree with others that we have to use the right tool for the job, but it’s nice to have this in our hip pocket.  Just as an FYI to anyone who has this issue, the filters do not appear in Safari 5.x nor are they present in SVG Edit… 

  • Simply Simpy

    For those who wish to stay with CSS, this is awesome:

    http://colorzilla.com/gradient-editor/

    • Reyescult

      This is hands down the best CSS Gradient generator tool I have found to date and it keeps getting better. I love this tool.

  • http://www.frivnew.com friv

    It has information I have been searching for a long time. Thanks so much.

  • John

    Good article, but I cannot get it to work in Firefox 3.6.23.
    Works fine in all the other browsers.

  • http://twitter.com/baamenabar Agustín Amenabar L.

    I was thinking you could build a php file that would render an SVG (being text it’s easy) so for a gradient background you could just specify dimensions and colours, like so:

    div.bar{

        background:
    url(gradient.php?height=20px&width=1px&angle=90&startColorRGBA=FF0000FF&endColorRGBA=0055FFFF)
    repeat-x 0 0;

    }

    just for simple gradients… and now that I think of it, one could even
    snif the browser and render PNG instead using the class for GD found
    here:

    http://planetozh.com/blog/my-projects/images-php-gd-gradient-fill/

    made by Ozh.

    or even better simply use ieX classes or the ones that Modernizr gives you to call PNG or SVG

    Anybody fancies something like that?

    one could even build rounded corner buttons and render them as PNG so everyone would see them… the thing is the overhead.

    Still, for simple gradients it could do the trick… you could save the
    gradient in a file, and then the code will first look for files like the
    one being called and if it’s not there it will build it and save it…

    If anyone is interested I could build the basics tonight…

    Do I make sense? or is it built already somewhere?

    let me know your thoughts.

  • Web design London

    Thank you so much for the info. Great blog

  • Tasman Hayes

    Thanks Alex! I’d been curious about SVG. I also didn’t know that some browsers can use SVG as backgrounds. This is one of the most interesting articles I’ve read all year.  :-)

  • Cheapuggsboots

    nice 

  • http://www.uggugg.us Cheapuggsboots

    leaning  

  • http://www.uggugg.us cheapuggsboots

    thank you for share ,but i don’t know how to do it . hmm….

  • http://Techreuters.com Dheeraj Bansal

    The best thing as an alternative to CSS3 rendering issues is to use Images.

  • http://www.aclearweb.co.uk Jan Cooper

    Phew – that looks time consuming!

  • Steve

    Wow.

    OK, I had bypassed on SVG numerous times in the past because I really have not seen any strong advantage over the canvas tag.

    I had been looking at this for nothing other than creating visible, simple shapes on a webpage… it had never really occurred to me to use it for the purposes that you’ve shown.

    I have to admit, the bricks were the real show stopper for me… I have been trying to do a similar trick using standard images, and I have to admit that my results have been far less clear, and far more bulky.

    Thank you!

  • Oswald

    Alex,

    I just found out that, contrary to what was posted in the live chat today, CSS4 does not exist;(

  • Dathan

    I’ve just spend the past several hours over two days struggling with SVG gradients – I tried several different method and came to the conclusion that SVG sucks for gradients because it doesn’t have rich support for color depth. A PNG-24 is still far superior.

    • Dathan

      I felt I should come back to correct myself. I had a 4 color gradient of slight variation and I exported it from Illustrator 5.5 and got a solid color. I put it SVG-edit and got a solid color. I converted it and tried the data-url and got a solid color. I discovered today http://www.colorzilla.com/gradient-editor/ and tried it, lo-and-behold the data-url works in IE9! I guess the other tools I used weren’t working. My bad on the former comment.

  • Dathan

    I felt I should come back to correct myself. I had a 4 color gradient of slight variation and I exported it from Illustrator 5.5 and got a solid color. I put it SVG-edit and got a solid color. I converted it and tried the data-url and got a solid color. I discovered today http://www.colorzilla.com/gradient-editor/ and tried it and lo-and-behold the data-url works in IE9! I guess the other tools I used weren’t working. My bad on the former comment. (Sorry if this is a repeat – is the reply working??)

  • fjpoblam

    As it turns out, there may be some instances in which SVG doen’t appear to help. Or maybe I’m simply using the G-hosted editor incorrectly. (Actually, the SVG code is pretty straightforward, so you might need the G-hosted editor only once or twice.)

    Anyway, this: I want to use a linear gradient for the entire html or body background. To make for a flexible layout (mobile-first!) I don’t want to specify a discrete size: just percentages. The G-hosted editor *seems* to demand a swath size and a “brush” size. As I see it, these might be inconsistent with unpredictable viewports in one CSS file.

  • http://www.gisassistans.se Anders Söderman Sweden

    Thanks Alex! I have spend several hundred hours with Inkscape & AI and I still have problems reading their SVG XML code. Now I get exactly the code I need to paste into other .SVG files.
    Please, when you make new versions of SVG-edit give the users a chance to reach 2.5 which is an easy start for beginners. Regards Anders Söderman Stockholm Sweden