CSS and XML: applying styles

CSS can be actually used to stylize XML documents. Anyway, there are a few gotchas to keep in mind when using CSS stylesheets with XML.

Default styles

Default styles (that is, styles used by the browser when none is specified) don't exist in XML. That's because XML has no predefined DTD to use when no stylesheet is provided. For example, if you don't specify any rule for the body element in XHTML, Firefox uses the following rule:

body {
  display: block;
  margin: 8px;
}

This is not the case of XML, where you have to esplicitly declare if every single element is a block-level element or not (or whatever type of display rule you want to be applied on it). Don't forget to do this, because browsers treat XML elements as inline by default, so you'll get only a single bunch of inline text by default.

Default algorithms

While browsers tend to adjust their algorithms with XHTML elements, they follow strictly CSS specifications with XML elements. So if a particular browser show a certain behavior for an XHTML element, you should not rely on this when it comes to XML.

Simply put, that means that if a browser doesn't fully implement a CSS feature, this lack of support will be shown entirely when dealing with XML elements. For example, suppose that you want to use relative and absolute positioning inside an XHTML table cell. CSS specifications say explicitly that this is an unpredictable behavior. Anyway, some browsers (like Opera), tend to adjust their rendering to prevent page layout from being broken. But this happens only with XHTML elements.

Instead, in XML you will see your layout completely broken and the positioned elements being scattered throughout the entire page. As a rule of thumb, you should always test if a feature if fully supported or not, or you might stumble on some strange surprises.

This entry was posted in , by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.