Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท At-rules

The @namespace at-rule

Reference for the CSS @namespace at-rule: declare XML namespaces so selectors can target SVG, MathML or XML elements by prefix, with a live example.

The @namespace at-rule declares an XML namespace (and optionally a prefix for it) so that selectors can tell elements with the same local name apart. It matters in documents that mix vocabularies, such as XML, XHTML with inline SVG or custom XML formats.

In ordinary HTML you almost never need it. HTML puts <a> and SVG's <a> in different namespaces, but the usual type selectors work without any declaration. Use @namespace when you must target one namespace specifically, using the prefix|name selector syntax.

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

svg|a { fill: blue; }

Try it

Select only SVG elements by namespace

Syntax

CSS
@namespace [<prefix>]? [<string> | url(<string>)];

@namespace url("http://www.w3.org/1999/xhtml");        /* default namespace */
@namespace svg url("http://www.w3.org/2000/svg");      /* prefixed */
  • Position: after @charset and @import, before any other rule.
  • Default namespace: without a prefix, it applies to type selectors that have no namespace part, so p then only matches p in that namespace.
  • Selector syntax: ns|name matches that namespace, *|name any namespace (including none), |name elements with no namespace.

Values

Syntax and arguments Description
@namespace svg url(...) Defines the prefix svg for use in selectors.
@namespace url(...) Defines the default namespace.
svg|circle A circle element in the declared SVG namespace.
*|circle A circle in any namespace.
|circle A circle with no namespace.
svg|* Any element in that namespace.

Usage notes

  • The prefix is local to the stylesheet. It does not need to match the prefix used in the document; only the namespace URL must match.
  • Beware of a default namespace. Setting a default namespace to something other than HTML's makes bare selectors like div stop matching HTML elements. Use prefixes in HTML pages.
  • Attribute selectors can be namespaced too: [xlink|href].
  • Must be early. A rule before @namespace makes it invalid.
  • Different from the xmlns attribute, which declares a namespace in the markup; @namespace only affects selectors.
  • Rarely needed. Prefer classes on SVG elements unless you really handle mixed XML.

Browser support

Supported in all modern browsers.