O'Reilly logo

SVG Colors, Patterns & Gradients by Kurt Cagle, Amelia Bellamy-Royds

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 7. Gradients in All Shapes and Sizes

So far, we’ve discussed how to create gradients, and how to position color and opacity stops in between the beginning (left) and end (right) of the gradient. Now, if all of your graphical needs involved gradients that went from left to right, then you’d be set. However, it’s likely that you might want gradients that go from top to bottom, or perhaps at a 60° angle, or otherwise transformed.

This chapter discusses the two ways in which you can control the position of a linear gradient, and also how you can control its scale. We’re going to assume you’re already comfortable with basic SVG shape elements (particularly <line>), coordinate systems, and transformations. There are a number of tricky little distinctions to be aware of, and once again there are details that differ between SVG and CSS, so we’ll be highlighting those as well.

One thing we can’t do much about is the significant quality differences between web browsers when it comes to how smoothly gradients are rendered. Particularly when using sharp color transitions, be sure to test your code to see if the results are acceptable.

The Gradient Vector

The first approach to positioning a gradient uses x1, y1, x2, and y2 attributes to position the start and end of the gradient, similar to drawing a line. By default, x2 is 100% and the other attributes are 0. If you drew a line with these attributes, it would go from left to right across the top of the drawing:

<line x1="0" y1=

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required