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.
@namespace svg url("http://www.w3.org/2000/svg"); svg|a { fill: blue; }
Try it
Syntax
@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
@charsetand@import, before any other rule. - Default namespace: without a prefix, it applies to type selectors that have no namespace part, so
pthen only matchespin that namespace. - Selector syntax:
ns|namematches that namespace,*|nameany namespace (including none),|nameelements 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
divstop matching HTML elements. Use prefixes in HTML pages. - Attribute selectors can be namespaced too:
[xlink|href]. - Must be early. A rule before
@namespacemakes it invalid. - Different from the
xmlnsattribute, which declares a namespace in the markup;@namespaceonly affects selectors. - Rarely needed. Prefer classes on SVG elements unless you really handle mixed XML.
Browser support
Supported in all modern browsers.