Chapter 4. Cascading Stylesheets

Table of Contents

Associating a CSS file with an XML document
Using the Cascade
Advanced CSS Selectors

When read by a browser, an XML document bears little relation to the HTML that it knows about by default, so we have to give it clues as to how it should display the elements we've created. We can do this in one of two ways, either giving it information on displaying existing tags, or translating the document into tags it knows about. To do the former, we use CSS, which should be a familiar technique from standard HTML.

A typical CSS stylesheet for an XML document might look like this:

Example 4.1. Simple CSS stylesheet for jokebook (excerpt)

  jokebook   {display:block}
 
  joke       {display:block}
 
  simplejoke {display:block;
              border:thin inset blue}
 
  question   {display:inline; 
              font-size:12pt; 
              font-weight:bold}
 
  punchline  {display:inline; 
              font-size:12pt; 
              font-style:italic}
  ...
			

Each entry in the stylesheet consists of a selector (e.g. jokebook with one or more properties (e.g. display:block) attached to it.

Each element must be defined in the stylesheet with its presentational properties. For each element in your DTD, you must define at least the display property, which governs how the element behaves on the page. If you set display:block then the element will be shown as an independent block of content, on its own line (behaving in a similar way to <p>, <h1>, etc.). Setting it to display:inline will make it behave more like characters on the page.

Other properties should be vaguely familiar to you if you've used CSS to format HTML before -- the actual formatting properties are the same for HTML and XML, and if you're used to using CSS with HTML then defining stylesheets for XML is much the same.

You'll also note that class selectors (the .myclass notation in CSS, which selects a class="myclass" attribute in the XHTML) are not commonly used, as there may be no class attribute defined in the DTD for the XML document. However, the xml:id attribute is often used for more specific cases, and as the markup is more semantic with better defined elements serving more specific purposes, so the absence of the class notation is rarely a problem.

Of course, you can also use any attribute as a selector, so for the following markup:

  <joke cert="18"> .... </joke>
                                

the following rule will prevent the joke being displayed:

  joke[cert="18"] {
      display: none;
  }