205-05

The :lang selector

Slide instructions

SPACEBAR to move forward through slides.

SHIFT & SPACEBAR to move backwards through slides.

LEFT ARROW & RIGHT ARROW to move through sections.

ESC to see overview and ESC again to exit.

F to enter presentation mode and ESC to exit.

Introduction

The :lang selector targets any element that contains the lang attribute and the relevant language subtag value.

Defining a language

All web documents should be defined with a language to assist devices, search engines and assistive technologies.

The primary language for each web document can be defined using the lang attribute inside the <html> element.


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Title</title>
  </head>
  <body>
    <h1>Hello world</h1>
  </body>
</html>

The lang attribute can be added to HTML elements to define languages for sections of a web document.


<!-- Italian -->
<div lang="it">
  Mi sei mancato molto
</div>!

<!-- Latvian -->
<span lang="lv">
  Labvakar
</span>

The values inside the lang attribute are called Language subtags.

These language subtags are defined in the IANA Language Subtag Registry.

The :lang selector (CSS2)

The :lang(c) pseudo-class selector is written using an optional element, followed by a ":", followed by "lang", followed by "(c)".

The "(c)" is a language subtag placed inside brackets.


/* syntax */
:lang(c) { }
E:lang(c) { }

/* French example */
p:lang(fr) { }
/* Punjabi example */
span:lang(pa) { }

Whitespace is not permitted within the selector.


/* Valid */
:lang(bs) { }

/* Invalid */
: lang (bs) { }

How does it work?

This selector targets any element that contains the lang attribute and the relevant language subtag value.

In the following example, only the <p> element with lang value of fr will be selected.


/* CSS selector */
p:lang(fr) { }

<!-- HTML markup -->
<p lang="fr">Adieu</p>
<p lang="jw">Sugeng rawuh</p>

Specifications

W3C Selectors Level 4
Status: Working Draft

Selectors Level 3
Status: Recommendation

CSS Level 2 (Revision 1)
Status: Recommendation

Support

The :lang(c) pseudo-class selector is not supported in IE6 or IE7.

Exercise 1: Write a :lang selector

Open this HTML file in an editor:
exercises-start/exercise-205-05-01.html

Write a CSS rule to style any element with a lang attribute to be color: plum. But only elements that have a language subtag of (fr).


/* Add styles here */
:lang(fr) {
  color: plum;
}

Check your work against the finished HTML file:
exercises-finished/exercise-205-05-01.html

Russ Weakley

Site Twitter Github Slideshare Linkedin

Next deck

205-06: The negation pseudo-class