Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

@namespace — namespaces in selectors

The @namespace rule binds a selector prefix to a namespace URI or establishes the default namespace for type selectors.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

@namespace <namespace-prefix>? [ <string> | <url> ];

@namespace [<prefix>]? <url-or-string>; declares a mapping consumed by selectors. After @namespace svg url("http://www.w3.org/2000/svg");, the selector svg|circle selects a circle specifically in the SVG namespace. *|circle accepts any namespace, while |circle accepts only no namespace. A rule without a prefix establishes the default namespace.

Namespace declarations must occur before style rules and after permitted prelude rules such as @import; a misplaced declaration is invalid. An undeclared prefix invalidates the selector. The URI is an identifier and is not a resource the browser has to fetch.

A default namespace affects type and universal selectors but does not change unprefixed attribute selectors: an unprefixed attribute still denotes no namespace. This distinction matters especially in XML and documents mixing HTML with SVG or MathML. The example creates a circle with createElementNS, matches it using svg|circle, and reads the actual computed fill and match marker.

Examples

const style = document.createElement('style');
style.textContent = `@namespace svg url("http://www.w3.org/2000/svg");
svg|circle { --namespace-match: yes; fill: rgb(0, 128, 0); }`;
document.head.append(style);
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
svg.append(circle);
document.body.append(svg);
const computed = getComputedStyle(circle);
console.log('match=' + computed.getPropertyValue('--namespace-match').trim() + '; fill=' + computed.fill);

Result

match=yes; fill=rgb(0, 128, 0)

The @namespace rule binds a selector prefix to a namespace URI or establishes the default namespace for type selectors.

Sources