Using SVG Embedded Stylesheets

   



Embedded Stylesheets and CDATA

The SVG document in Listing 2.9 uses an internal stylesheet in order to define the colors of a pair of nested rectangles as illustrated in Figure 2.6.

Listing 2.9 style2.svg

start example
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20001102//EN"  "http://www.w3.org/TR/2000/CR-SVG-20001102/DTD/svg-20001102.dtd"> <svg width="800" height="500"> <style type="text/css"> <![CDATA[ rect {   stroke-width:4;   stroke:blue;   fill:red; } ]]> </style>   <rect x="50"  y="50"  width="200" height="200"/>   <rect x="100" y="100" width="100" height="100"/> </svg>
end example

Remarks

The stylesheet definition in Listing 2.9 is embedded in a CDATA section, which starts with the following lines:

<style type="text/css"> <![CDATA[

The first line declares that the style is of type text/css, which means that what will follow consists of CSS (Cascading Style Sheet) rules. The second line contains the string CDATA, which refers to 'character data,' and it prevents the SVG viewer from interpreting the characters inside the CDATA section as XML. If you've worked with Unix shell scripts or Perl scripts, this might remind you of a 'here' document. By the way, you'll see CDATA sections used for SVG documents that contain JavaScript/ECMAScript. Notice that the matching pair of lines is in the correctly nested order as shown below:

]]> </style>

Now let's look at the contents of the stylesheet given in the following fragment:

rect {   stroke-width:4;   stroke:blue;   fill:red; }

The attributes above are simply name/value pairs that can be interpreted as 'for any rectangle, use a width of four pixels when rendering its perimeter with the color blue; the fill color for inside a rectangle is red.' These attributes are applied to every occurrence of the SVG rect element in the SVG document, which means that the SVG rect elements do not need to specify the attributes that are defined in the stylesheet. Moreover, the process of adding, removing, or modifying attribute values becomes very straightforward; simply make the necessary change in the stylesheet and those modifications will be applied to the corresponding elements. The stylesheet in Listing 2.9 can easily be extended to other SVG elements.



   



Fundamentals of SVG Programming. Concepts to Source Code
Fundamentals of SVG Programming: Concepts to Source Code (Graphics Series)
ISBN: 1584502983
EAN: 2147483647
Year: 2003
Pages: 362

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net