Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 139 ยท Selectors

Rarely Used Selectors: :lang(), :dir(), :scope and @namespace

Learn four selector features you will meet less often, :lang(), :dir(), :scope and @namespace, with working examples for multilingual, right-to-left and SVG pages.

Most of your CSS will use classes, a few combinators and the usual pseudo-classes. But the selector toolbox has a few corners that most tutorials skip, and they solve real problems the moment your site leaves a single-language, left-to-right, HTML-only world.

This lesson covers four of them. :lang() styles text by its language, :dir() styles it by its writing direction, :scope means "the element I started from", and @namespace lets a selector tell HTML elements and SVG elements apart. You will not use them every day, but knowing they exist saves you from fragile workarounds.

:lang(): style by language

The :lang() pseudo-class matches elements by the language they are written in. The browser works out an element's language from the nearest lang attribute, looking at the element itself and then its ancestors. That means one lang="fr" on a <section> marks everything inside it as French, with no extra markup.

HTML
<html lang="en">
  <body>
    <p>Hello.</p>
    <blockquote lang="fr">
      <p>Bonjour.</p>      <!-- inherits French from the blockquote -->
    </blockquote>
  </body>
</html>
CSS
p:lang(fr) { font-style: italic; }

The second paragraph matches, even though it has no lang attribute of its own. That inheritance is the big difference from the attribute selector [lang="fr"], which only sees the element that carries the attribute (see Attribute Selectors).

Regions, lists and wildcards

:lang(fr) also matches regional variants such as fr-CA and fr-BE, because language tags are hierarchical. Writing :lang(fr-CA) narrows it to Canadian French only.

The specification also allows a comma-separated list, :lang(en, de), and quoted wildcards such as :lang("*-CH"). Support for those forms is uneven: Chromium-based browsers rejected them when this lesson was written, and one rejected selector invalidates the whole rule. For code that must work everywhere, use one language per :lang() and combine them with :is():

CSS
:is(:lang(en), :lang(de)) { hyphens: auto; }    /* English or German */
:lang(fr-CA) { quotes: "\00AB\00A0" "\00A0\00BB"; } /* Canadian French only */

What :lang() is good for

Language-aware styling is the main reason to reach for it:

  • Quotation marks. Each language quotes differently. Set quotes once per language and every <q> on the page follows.
  • Fonts. A Latin font rarely has Japanese or Arabic glyphs, and a fallback font may look odd. Choose a font stack per language.
  • Typography rules. Italics read badly in Chinese and Japanese, hyphens: auto needs the right dictionary, and line height often needs to be taller for scripts with tall glyphs.
Quotes and typography per language

Look at the German row: :lang(de) matched de-CH for the quotation marks and, through :is(), for the double border, which the Portuguese row gets too. The French em turned red because its row div carries lang="fr-CA", which the em inherits.

:lang() only helps when the lang attribute is correct. Put lang on <html>, and add it to any passage in another language. That also helps screen readers pick the right voice, so it is an accessibility fix and a styling hook at once.

:dir(): style by writing direction

Hebrew, Arabic and several other scripts run right to left. HTML records this with the dir attribute (ltr, rtl or auto), and :dir() lets CSS react to the resolved direction of an element:

CSS
:dir(rtl) .arrow { transform: scaleX(-1); }

This differs from [dir="rtl"] in two ways. First, direction is inherited, so :dir(rtl) matches every element inside a right-to-left container, while the attribute selector matches only the one element carrying it. Second, dir="auto" is resolved by the browser from the text itself: an element with dir="auto" whose first strong character is Arabic matches :dir(rtl), but never matches [dir="rtl"].

Note what :dir() does not look at: the CSS direction property. It reflects the document's dir attribute. For markup that carries meaning, set direction in HTML, not CSS.

Before you reach for :dir(), check whether logical properties already solve the problem. margin-inline-start, padding-inline-end and text-align: start flip on their own. :dir() is for the things logical properties cannot flip, such as an arrow glyph, a directional icon, a gradient angle or an asymmetric shadow.

Flipping a directional icon with :dir()

All three rows get correct layout from margin-inline-start. The arrow flips on the second and third rows because :dir(rtl) matches them, but only the second row gets the dashed border: the third row's direction was resolved from its Hebrew text, which [dir="rtl"] cannot see.

:scope: "the element I started from"

:scope is a pseudo-class whose meaning depends on where the selector is used:

Where What :scope matches
A normal stylesheet rule The root element, <html>, the same as :root
element.querySelector(), querySelectorAll(), matches(), closest() The element you called the method on
Inside an @scope rule The scope root you named

In a plain stylesheet, :scope is just a roundabout way to write :root, so you will almost never type it there. Its real value is in JavaScript. Selectors passed to querySelectorAll() are matched against the whole document, and only the results are limited to the element's descendants. That causes a classic surprise: you cannot easily say "only my direct children".

:scope fixes that:

JavaScript
const list = document.querySelector("ul.menu");
list.querySelectorAll("li");            // every li, including nested submenus
list.querySelectorAll(":scope > li");   // only the direct children of this list
:scope in querySelectorAll

Without :scope, the second query would need a clumsy workaround such as Array.from(menu.children). With it, the selector reads the way you think about the problem. In @scope rules the same idea carries into CSS: :scope there is the root element you scoped to, and you can write :scope > .title to style only its direct children.

@namespace: HTML and SVG in one stylesheet

Elements belong to namespaces. In an HTML page, ordinary elements are in the XHTML namespace, and an inline <svg> and everything inside it is in the SVG namespace. Usually that is invisible, because CSS type selectors match a name in any namespace. A selector a hits both HTML links and SVG links. title matches the HTML page title and an SVG <title>. When that causes a clash, @namespace lets you be precise.

Declare a prefix at the top of your stylesheet, right after any @charset and @import, and then separate prefix and name with a pipe:

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

svg|a { text-decoration: underline; }  /* SVG links only */
*|a   { color: #1d4ed8; }              /* links in any namespace (the default) */
|a    { font-weight: 700; }            /* elements with no namespace at all */

The prefix belongs to the stylesheet and has nothing to do with the prefix used in markup. The URL is what counts. Attribute selectors can use namespaces too: [xlink|href] targets the legacy xlink:href attribute on SVG elements.

The default-namespace trap

A declaration with no prefix sets the default namespace, and from then on every unprefixed type selector matches only that namespace:

CSS
@namespace url("http://www.w3.org/1999/xhtml");

a { color: red; }   /* now matches HTML links only, SVG links no longer match */

That is a common reason an old stylesheet "suddenly stops styling" SVG, often after someone adds a framework that includes such a rule. Use *|name when you need the old behavior back.

The default namespace changes what a matches

The HTML link is crimson and the SVG label is violet, though both are a elements. @namespace is also covered, together with the other at-rules that must come first, in CSS At-rules Overview.

Which one do I need?

You want to... Use
Change quotes, fonts or hyphenation per language :lang()
Flip an icon or gradient for right-to-left text :dir() (after trying logical properties)
Select only the direct children of an element in JavaScript :scope > ...
Style HTML and SVG elements with the same name differently @namespace and `svg

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A page has <section lang="fr"><p>Salut</p></section>. Which selectors match the paragraph?

    :lang() uses the inherited language, so the paragraph matches. [lang="fr"] only matches an element that has the attribute itself.
  2. 2. Which selector matches French text of any region, such as fr-CA and fr-BE?

    Language tags are hierarchical, so :lang(fr) also matches regional variants.
  3. 3. Why can :dir(rtl) match an element that [dir="rtl"] does not?

    :dir() reflects the direction the element actually has, whether it was set on it, inherited from an ancestor or worked out from the text by dir="auto".
  4. 4. What does list.querySelectorAll(":scope > li") return?

    In DOM methods, :scope is the element you called the method on, so :scope > li means its direct li children.
  5. 5. After @namespace url("http://www.w3.org/1999/xhtml");, what does the selector a match?

    A declaration without a prefix sets the default namespace, so unprefixed type selectors match only that namespace. Use *|a to match any namespace.

Summary

  • :lang() matches by the inherited language of an element, including regions; combine several languages with :is(). Use it for quotes, fonts and hyphenation.
  • :dir(ltr) and :dir(rtl) match the resolved writing direction. Prefer logical properties, and use :dir() for icons and effects they cannot flip.
  • :scope is the root in a stylesheet, but in querySelectorAll() it is the element you called it on, so :scope > li gets direct children.
  • @namespace declares a prefix for svg|a style selectors, and an unprefixed declaration changes what plain type selectors match.

Next: The Cascade.