W3C

Bert Bos | CSS tutorial – XML Namespaces

CSS namespaces for XML

CSS support for XML namespaces

Namespaces in XML

<title>Embedding</title>
<data>
 <card xmlns="http://example.com/people">
  <title>Professor</title>
  <name>Ben<name>
 </card>
</data>

Some XML-based formats allow elements from other XML-based formats to be mixed-in, usually in restricted ways. E.g., MathML allows annotations on mathematical formulas, which may themselves be in some other XML-based format.

To distinguish the elements from the host language from those borrowed from some other language, XML defines a special attribute “xmlns”, whose value is a URL. The URL is the “namespace of the element”. The namespace is inherited by child elements in the tree.

That's particularly useful if the host language and the embedded fragment have elements with the same name (like “title” in the example above).

CSS selectors can select elements by their namespace. E.g., the two “title” elements in the example can be distinguished by their context (one is inside a card element, the other isn't), but it may be easier in some cases to distinguish them by their namespace.

CSS namespaces for XML

Define a name for the namespace:

@namespace x url(http://example.com/ns1);

Use it in a selector:

x|title { color: red }

Useful for certain XML-based formats.

The name is arbitrary, it need not be the same as the prefix in the XML document that you are styling.

Defined names are only valid in the current style sheet, not in any @imported style sheets, nor in any style sheets that @import this one.

The URL must have valid CSS syntax for URLs (which is very lenient). CSS neither dereferences it nor checks if it has a known protocol. It is only used as a literal string to compare against a namespace in an XML file.

Special namespaces