Home > Articles

Styling SVG

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Organizing Your Style Sheet

Organization of your style sheet is critical to both efficient coding and collaborative environments. Oftentimes, your SVG file will contain dozens (if not hundreds) of selectors. Because of this, it becomes very difficult to quickly scan over a list of selectors that do not clearly define what their style declarations accomplish or are not grouped according to accomplishment.

In collaborative development environments, where multiple developers and designers are working with the same SVG file (or a group thereof), having style sheets clearly labeled and organized can severely decrease the number of duplicate styles.

For instance, if you had a style sheet with ten rules that represented different fill colors, four classes that represented four stroke colors, and two rules that determined an object's visibility, you would need to group these classes according to their function.

In Listing 6.8, all four stroke color rules are positioned together within the style sheet on lines 9 through 12. The fill rules are together on lines 14 through 23, and two display rules are positioned on lines 25 and 26.

Listing 6.8 Grouping Style Classes

01: <?xml version="1.0" standalone="no"?>
02: <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
03:  "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
04:
05: <svg width="500" height="300">
06:
07: <style type="text/css">
08:   <![CDATA[
09:     .StrokeGreen{stroke:green;}
10:     .StrokeYellow{stroke:yellow;}
11:     .StrokePurple{stroke:purple;}
12:     .StrokeOrange{stroke:orange;}
13:
14:     .FillGreen{fill:green;}
15:     .FillYellow{fill:yellow;}
16:     .FillPurple{fill:purple;}
17:     .FillOrange{fill:orange;}
18:     .FillBlue{fill:blue;}
19:     .FillPink{fill:pink;}
20:     .FillBrown{fill:brown;}
21:     .FillRed{fill:red;}
22:     .FillBlack{fill:black;}
23:     .FillWhite{fill:white;}
24:
25:     .DisplayInline{display:inline;}
26:     .DisplayNone{display:none;}
27:   ]]>
28: </style>
29:
30:   <path class="StrokeGreen FillYellow DisplayInline"
        d="M150,140
        c 0,0 -16,24 -16,33
        c 0,9 7,15 16,15
        c 9,0 16,-7 16,-15
        c 0,-9 -16,-33 -16,-33"/>
31:
32:   <path class="StrokeGreen DisplayNone"
        d="M250,140
        c 0,0 -16,24 -16,33
        c 0,9 7,15 16,15
        c 9,0 16,-7 16,-15
        c 0,-9 -16,-33 -16,-33"/>
33:
34: </svg>

Note the new style commands that were added in lines 25 and 26: display:inline and display:none. In Hour 5, you learned how to prevent some of your elements from displaying by commenting them out of your code. Using the display property, however, allows you a much more efficient method of enabling or disabling the rendering of your elements.

  • + Share This
  • 🔖 Save To Your Account