Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
The :lang Pseudo-class in CSS
The CSS :lang() pseudo-class selector is used to select elements with a specific lang attribute. This helps target content in different languages and style them accordingly, making it useful for multilingual websites.
Syntax
:lang(language-code) {
/* CSS declarations */
}
The language code is typically a two-letter ISO language code such as en for English, es for Spanish, or it for Italian.
Example: Basic Language Targeting
The following example shows how to style text differently based on language −
<!DOCTYPE html>
<html>
<head>
<style>
p {
padding: 10px;
margin: 5px 0;
border: 1px solid #ccc;
}
p:lang(it) {
background-color: #e8f5e8;
color: #2d5a2d;
}
p:lang(en) {
background-color: #e8e8f5;
color: #2d2d5a;
}
p:lang(es) {
background-color: #f5e8e8;
color: #5a2d2d;
}
</style>
</head>
<body>
<p lang="it">Ciao, come stai?</p>
<p lang="en">Hello, how are you?</p>
<p lang="es">Hola, ¿cómo estás?</p>
</body>
</html>
Three paragraphs appear with different background colors: Italian text has a light green background, English text has a light blue background, and Spanish text has a light red background.
Example: Adding Language Labels
Using the ::after pseudo-element with :lang() to add language labels −
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: 10px;
padding: 15px;
text-align: center;
border: 1px solid #333;
font-weight: bold;
}
div:lang(it)::after {
content: " ~ Italian";
font-style: italic;
color: #666;
}
div:lang(es)::after {
content: " ~ Spanish";
font-style: italic;
color: #666;
}
div:lang(nl)::after {
content: " ~ Dutch";
font-style: italic;
color: #666;
}
/* Flag-inspired backgrounds */
div:lang(it) {
background: linear-gradient(90deg, #00ae00 33.3%, white 33.3%, white 66.6%, red 66.6%);
}
div:lang(es) {
background: linear-gradient(red 25%, yellow 25%, yellow 75%, red 75%);
}
div:lang(nl) {
background: linear-gradient(90deg, red 33.3%, white 33.3%, white 66.6%, blue 66.6%);
}
</style>
</head>
<body>
<div lang="it">Rome</div>
<div lang="es">Madrid</div>
<div lang="nl">Amsterdam</div>
</body>
</html>
Three boxes appear with flag-inspired backgrounds and city names, each followed by their respective language labels in italic gray text.
Conclusion
The :lang() pseudo-class is essential for creating language-specific styles in multilingual websites. It allows you to target content based on the lang attribute and apply appropriate styling for better user experience.
