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.. |
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 its native file format. It rightly has lots of fans, but might be overkill for producing simple web-ready graphics.
- BoxySVG: My personal favorite, BoxySVG is a super powerful, cost effective editor that keeps you connected to the code.
- SVG Edit: The old classic,
Google’sPavol Rusnak’s SVG Edit (hosted on Google Code) is simple but effective.
- It’s free, and we always like free.
- 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.
- It writes tight, clean, readable markup.
- SVG Edit is designed to keep you in close contact with the SVG code all the way through the process.
Example 1: Simple linear gradients
1. Open SVG Edit in your browser (from the link the Demos section).![The blank SVG Edit](https://uploads.sitepoint.com/wp-content/uploads/2011/08/svg-edit.png)
<svg width="640" height="480" xmlns="https://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="https://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)
What about Radial Gradients?
![](https://lh6.googleusercontent.com/-TryuxuYe-LY/Th48WjMVGDI/AAAAAAAAFTk/IHKdRl8lRQI/SVG%252520edit1-radial.jpg)
![Billy Wilder's 'Sunset Boulevard' 1950 - http://en.wikipedia.org/wiki/Sunset_Boulevard](https://uploads.sitepoint.com/wp-content/uploads/2011/09/sunset.jpg)
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](https://uploads.sitepoint.com/wp-content/uploads/2011/09/seamless-brick.jpg)
![Radial gradients in SVG](https://uploads.sitepoint.com/wp-content/uploads/2011/09/svg.jpg)
<svg width="640" height="480" xmlns="https://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.](https://uploads.sitepoint.com/wp-content/uploads/2011/09/heyteacher.jpg)
- Chrome (since May 2010)
- Firefox (March 2011)
- IE9 (March 2010 beta)
- Safari (June 2010)
- Opera (June 2008).
Example 3 – Vintage gallery
![](https://uploads.sitepoint.com/wp-content/uploads/2011/09/polygon-tool.jpg)
![The blur filter](https://uploads.sitepoint.com/wp-content/uploads/2011/09/blurfilter.jpg)
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](https://uploads.sitepoint.com/wp-content/uploads/2011/09/photopaper.jpg)
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](https://uploads.sitepoint.com/wp-content/uploads/2011/09/gallery.jpg)
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 thebackground-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!
Frequently Asked Questions (FAQs) about CSS3 Gradients
What are CSS3 gradients and why are they important?
CSS3 gradients are a feature of CSS3 that allows developers to display smooth transitions between two or more specified colors. They are important because they can enhance the visual appeal of a website without the need for images, which can slow down page load times. CSS3 gradients can be used in various elements, including backgrounds, borders, and text.
How do CSS3 gradients differ from image gradients?
Unlike image gradients, CSS3 gradients are generated by the browser, which means they can be scaled to any size without loss of quality. They also require less bandwidth and load faster than image gradients. Additionally, CSS3 gradients can be animated and modified using CSS, providing more flexibility and control to developers.
How can I create a CSS3 gradient?
To create a CSS3 gradient, you can use the linear-gradient()
or radial-gradient()
function in your CSS code. These functions allow you to specify the direction and colors of the gradient. For example, background: linear-gradient(to right, red, orange);
will create a linear gradient that transitions from red to orange from left to right.
What are the different types of CSS3 gradients?
There are two main types of CSS3 gradients: linear and radial. Linear gradients transition colors along a straight line, while radial gradients transition colors in a circular pattern. Each type can be customized with different directions and color stops.
Can I use CSS3 gradients in all browsers?
CSS3 gradients are supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. However, for older versions of Internet Explorer, you may need to use fallbacks or vendor prefixes to ensure compatibility.
How can I animate a CSS3 gradient?
CSS3 gradients can be animated using CSS animations or transitions. For example, you can change the colors or direction of the gradient over time, or animate the background position to create a moving gradient effect.
Can I use CSS3 gradients with text?
Yes, you can apply CSS3 gradients to text using the background-clip
property with the value text
. This will clip the background to the shape of the text, creating a gradient effect.
What are color stops in CSS3 gradients?
Color stops are the colors you want to render smooth transitions among. You can also specify the position of each color stop to control where each color starts and ends.
How can I create a radial gradient with CSS3?
To create a radial gradient, you can use the radial-gradient()
function. This function allows you to specify the shape, size, position, and colors of the gradient. For example, background: radial-gradient(circle, red, orange);
will create a circular gradient that transitions from red in the center to orange at the edges.
What are the best practices for using CSS3 gradients?
Some best practices for using CSS3 gradients include using them sparingly to avoid visual clutter, providing fallbacks for older browsers, and testing your gradients in different browsers to ensure they look as intended.
![Alex Walker](https://uploads.sitepoint.com/wp-content/uploads/2022/06/1654759884aw-508-120x120.png)
Alex has been doing cruel and unusual things to CSS since 2001. He is the lead front-end design and dev for SitePoint and one-time SitePoint's Design and UX editor with over 150+ newsletter written. Co-author of The Principles of Beautiful Web Design. Now Alex is involved in the planning, development, production, and marketing of a huge range of printed and online products and references. He has designed over 60+ of SitePoint's book covers.