Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Selectors

Namespace separators (ns|element)

Reference for CSS namespace selectors: ns|element, *|element and |element, declared with @namespace, for styling XML and SVG in mixed-namespace documents.

A namespace separator is the vertical bar (|) in a selector. It limits a type or attribute selector to elements from a particular XML namespace, which you first declare with the @namespace at-rule. It matters in XML, XHTML, and documents that mix vocabularies such as HTML, SVG and MathML.

In ordinary HTML pages you almost never need it. The HTML parser puts elements in the right namespace automatically, and a plain circle or a selector works.

CSS
@namespace svg url(http://www.w3.org/2000/svg);

svg|a { fill: blue; }

Try it

Namespaces in inline SVG

Both namespaces here are bound to prefixes, so ordinary selectors such as body are unaffected. A @namespace rule with no prefix would instead set the default namespace. Prefixes (svg, html) are local to the stylesheet; they need not match prefixes in the document.

Syntax and arguments

CSS
@namespace url(http://www.w3.org/1999/xhtml);   /* default namespace */
@namespace svg url(http://www.w3.org/2000/svg); /* prefixed */

svg|circle { }   /* circle in the svg namespace */
*|circle { }     /* circle in any namespace, or none */
|circle { }      /* circle with no namespace */
[xlink|href] { } /* attribute in a namespace */
Form Description
ns|name Only elements named name in the namespace bound to ns.
*|name name in any namespace, including none.
|name name in no namespace.
name If a default namespace was declared, only that namespace; otherwise any.
ns|* Every element in that namespace.

@namespace rules must appear after @charset and @import and before all other rules.

Usage notes

  • Rarely needed. In HTML documents there is no practical difference between svg|circle and circle. Use namespaces when styling standalone XML, or when a name occurs in several vocabularies, such as a in HTML and SVG.
  • Declaring a default namespace changes meaning. After @namespace url(...xhtml), a bare p matches only XHTML paragraphs. If you declare a default that does not match your elements, plain type selectors stop matching.
  • Attribute selectors. [xlink|href] targets attributes in a namespace; unprefixed attribute names are in no namespace, so the default namespace does not apply to them.
  • Not for custom prefixes in HTML. <svg:circle> written in HTML source is not parsed as namespaced; the colon stays part of the tag name.
  • Escape the bar in JavaScript. querySelector has no way to declare namespaces, so it cannot use ns|name selectors (other than *|name).

Browser support

Supported in all major browsers, though it is seldom used in HTML-only sites.