Why CSS class and ID selectors don't always work in XML

This is a question that sometimes may arise in forums and mailing lists, especially when innocent developers try to stylize their first XML documents. A simple answer to this question is provided by the CSS specification itself, when it states that:

In XML 1.0, the information about which attribute contains an element's IDs is contained in a DTD. When parsing XML, UAs do not always read the DTD, and thus may not know what the ID of an element is.

http://www.w3.org/TR/CSS21/selector.html#id-selectors

The same remarks apply to the class attribute as well. Web developers accustomed to XHTML, which has a predefined DTD and stores element attributes in an ATTLIST element, find this difference quite confusing.

They say: "But wait, we can specify a custom DTD for our XML documents, can't we? So if we specify id and class attributes in an ATTLIST, then this problem will be fixed".

Unfortunately, this is far from being the truth. Today's browsers don't use a validating parser, so they don't treat XML attributes as they do with their XHTML counterparts. In other words, even if you specify id and class attributes in your DTD, a browser won't consider them as special attributes (as in XHTML). No "magic" here.

To fix this problem, we should use attribute selectors instead of ID and class selectors: for example, book[id="b1"] instead of #b1, or price[class="special"] instead of .special.

Bear in mind, however, that the specificity of attribute selectors is lower than ID and class selectors, so it may be necessary to add an !important statement to the declarations:

  1. book[id="b1"] {
  2. color: green !important;
  3. }

Leave a Reply

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