Colors and Opacity


Colors can be expressed in two ways in an SVG document: by name or by the amount of red, green and blue in a color.

Color Names

A list of named colors is provided by the SVG specification.

RGB Colors

You can also write colors in the following form rgb(A,B,C) where A, B and C are non-negative integers less than or equal to 255. The values of A, B and C represent the respective amounts of red, green and blue in the color. A similar way to write colors is as a triple of three percentages rgb(A%,B%,C%). Here A, B and C. The following example illustrates both:

image of a circle
Your browser did not display the SVG image. It is showing a standard image as a fallback.
Source of rgb.svg:Hide line numbers
1: <svg version="1.1" baseProfile="full"
2:      xmlns="http://www.w3.org/2000/svg" 
3:      width="300px" height="200px" viewBox="0 0 300 200">
4:      
5:    <rect x="0" y="0" width="300" height="200" fill="rgb(100%,100%,0%)"/>
6:    <circle cx="150" cy="100" r="80" fill="rgb(0,0,255)" stroke="rgb(75%,75%,100%)" stroke-width="10px"/>
7:    
8: </svg>
9: 

Opacity

You can set the opacity (opposite of transparency) of an object (or group of objects) using the opacity attribute. The attribute takes values between zero and one (inclusive).

You can also set the opacity of the stroke and fill portions of the rendering of an object using the attributes stroke-opacity and fill-opacity. Note that stroke operations are drawn after fill operations, so setting both these attributes the same gives a different effect than just using the opacity attribute. See the following example:

image of a circle
Your browser did not display the SVG image. It is showing a standard image as a fallback.
Source of opacity.svg:Hide line numbers
1: <svg version="1.1" baseProfile="full"
2:      xmlns="http://www.w3.org/2000/svg" 
3:      width="300px" height="200px" viewBox="0 0 300 200">
4:      
5: <circle cx="100" cy="100" r="95" fill="orange" stroke="blue" stroke-width="5px"/>
6: <ellipse cx="200" cy="50" rx="95" ry="45" fill="green" stroke="black" stroke-width="10px" stroke-opacity="0.25" fill-opacity="0.75"/>
7: <ellipse cx="100" cy="150" rx="95" ry="45" fill="red" stroke="purple" stroke-width="10px" opacity="0.5"/>
8: 
9: </svg>

Remark: Opacity does not convert well into PDFs. (Wikipedia's article on transparency explains why.)

SVG 2

The draft of version 2 of the SVG specification allows for more possibilities for defining colors. For instance, it allows HSL colors, which I find more intuitive. See the draft's Color Syntax Description. You can probably get away with using this in most modern browsers, but I wouldn't recommend doing this unless you really need it.


This presentation is part of a SVG Tutorial for Mathematics Students.


© 2013 by W. Patrick Hooper. This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. Creative Commons License Valid XHTML 1.0 Strict Valid CSS!