Css based on html lang

:lang()

The :lang() CSS pseudo-class matches elements based on the language they are determined to be in.

Try it

Syntax

Formal syntax

Parameters

A comma separated list of one or more s that target an element with a language value according to BCP 47 language codes. Matching by language range is case-insensitive.

Description

When selecting languages, there is implicit wildcard matching, so :lang(de-DE) will match de-DE , de-DE-1996 , de-Latn-DE , de-Latf-DE , and de-Latn-DE-1996 . Explicitly using wildcards must include a full match of a language subtag, so :lang(«*-F*») is invalid but :lang(«*-Fr») is valid.

Examples

Matching children of a given language

In this example, the :lang() pseudo-class is used to match the parents of quote elements ( ) using child combinators. Note that this doesn’t illustrate the only way to do this, and that the best method to use depends on the type of document. Also note that Unicode values are used to specify some of the special quote characters.

HTML

div lang="en"> q>This English quote has a q>nestedq> quote inside.q> div> div lang="fr"> q>This French quote has a q>nestedq> quote inside.q> div> div lang="de"> q>This German quote has a q>nestedq> quote inside.q> div> 

CSS

:lang(en) > q  quotes: "\201C" "\201D" "\2018" "\2019"; > :lang(fr) > q  quotes: "« " " »"; > :lang(de) > q  quotes: "»" "«" "\2039" "\203A"; > 

Result

Matching multiple languages

The following example shows how to match multiple languages by providing a comma-separated list of language codes. It’s also possible to use a wildcard to match languages in a given language range.

CSS

/* Matches nl and de */ :lang("nl", "de")  color: green; > /* Omitting quotes & case-insensitive matching */ :lang(EN, FR)  color: blue; > /* Wildcard matching a language range */ :lang("*-Latn")  color: red; > 

HTML

p lang="nl">Dit is een Nederlandse paragraaf.p> p lang="de">Dies ist ein deutscher Satz.p> p lang="en">This is an English sentence.p> p lang="en-GB">Matching the language range of English.p> p lang="fr">Ceci est un paragraphe français.p> p lang="fr-Latn-FR">Ceci est un paragraphe français en latin.p> 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • The :dir pseudo-class that matches by directionality of text
  • HTML lang attribute
  • HTML translate attribute
  • RFC 5646: Tags for Identifying Languages (also known as BCP 47)

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

:lang

Задавайте стили тексту в зависимости от языка, на котором он написан.

Время чтения: меньше 5 мин

Обновлено 13 декабря 2021

Кратко

Скопировать ссылку «Кратко» Скопировано

Псевдокласс :lang выбирает элементы, в зависимости от их языка, который определяется комбинацией атрибута lang , тега и иногда информацией из протокола передачи данных (такой, как заголовки HTTP).

Пример

Скопировать ссылку «Пример» Скопировано

Предложениям будут присвоены стили, в зависимости от языка, который указан в атрибуте lang тега .

   

Der Mensch, versuche die Gotter nicht.

Ce que femme veut, Dieu le veut.

То be or not to be.

blockquote lang="de"> p>Der Mensch, versuche die Gotter nicht.p> blockquote> blockquote lang="fr"> p>Ce que femme veut, Dieu le veut.p> blockquote> blockquote lang="en"> p>То be or not to be.p> blockquote>
 blockquote p::before  content: open-quote;> blockquote p::after  content: close-quote;> blockquote:lang(de)  quotes: "„" "“";> blockquote:lang(fr)  quotes: "«" "»";> blockquote:lang(en)  quotes: "“" "”";> blockquote p::before  content: open-quote; > blockquote p::after  content: close-quote; > blockquote:lang(de)  quotes: "„" "“"; > blockquote:lang(fr)  quotes: "«" "»"; > blockquote:lang(en)  quotes: "“" "”"; >      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

После любого селектора ставим двоеточие и пишем ключевое слово lang . В скобках указываем, для какого языка применяются правила. Список доступных языков можно посмотреть в ISO 639-1 Language Codes.

 p:lang(es)  background-color: orange; font-size: 16px;> p:lang(es)  background-color: orange; font-size: 16px; >      

Как понять

Скопировать ссылку «Как понять» Скопировано

Иногда на странице текст может состоять из разных языков, например основной текст написан на русском, но имеет цитаты на английском. В этом случае с помощью :lang можно придать особое оформление конкретному языку.

Подсказки

Скопировать ссылку «Подсказки» Скопировано

 

слово

palabra

cześć

p>q lang="ru">словоq>p> p>q lang="es">palabraq>p> p>q lang="pl">cześćq>p>

Источник

Styling using language attributes

What is the most appropriate way to associate CSS styles with text in a particular language in a multilingual HTML or XML document?

Presentation styles are commonly used to control changes in fonts, font sizes and line heights when language changes occur in the document. This can be particularly useful when dealing with Simplified versus Traditional Chinese, where users tend to prefer different fonts, even though they may be using many of the same characters. It can also be useful to better harmonize the look of mixed, script-specific fonts, such as when mixing Arabic and Latin fonts.

This page looks at available options for doing this most effectively.

Quick answer

The best way to style content by language in HTML is to use the :lang selector in your CSS style sheet. For example:

The important point to be made in this section is that this would not be possible using the [lang|=». «] or [lang=». «] selectors. For those to work you would have to declare the language explicitly on each Japanese em tag.

This is a significant difference between the usefulness of these different selectors.

Which language attribute?

The lang attribute is used to identify the language of text served as HTML. Text served as XML should use the xml:lang attribute.

For XHTML that is served as text/html, it is recommended that you use both attributes, since the HTML parser will pick up on the lang attribute, whereas if you parse the content as XML the xml:lang attribute will be used by your XML parser.

The article will first discuss the various options for styling by language in HTML, using the lang attribute. There then follows a section about how to style XML documents based on xml:lang .

The :lang(. ) pseudo-class selector

could have the following styling:

body :lang(ar) :lang(zh-Hant) :lang(zh-Hans) :lang(din)

The Greek and Russian use the styling set for the body element.

This is the ideal way to style language fragments, because it is the only selector that can apply styling to the content of an element when the language of that content is declared earlier in a page.

A rule for :lang(zh) would match elements with a language value of zh . It would also match more specific language specifications such as zh-Hant , zh-Hans and zh-TW .

The selector :lang(zh-Hant) will only match elements that have a language value of zh-Hant or have inherited that language value. If the CSS rule specified :lang(zh-TW) , the rule would not match our sample paragraph.

A [lang|=». «] selector that matches the beginning of a value of an attribute

For markup example we saw in the previous section, the style sheet could be written as:

body *[lang|="ar"] *[lang|="zh-Hant"] *[lang|="zh-Hans"] *[lang|="din"]

Unlike :lang , this selector will only work for elements which carry a lang attribute (see Inheritance of language values).

There is a significant difference between this selector and [lang=». «] . Whereas [lang=». «] will only match elements when the selector value and the attribute value are identical, this selector value will match a language attribute value that has additional hyphen-separated values. Therefore the selector [lang|=»sl»] would match sl-IT , sl-nedis or sl-IT-nedis , and the selector [lang|=»zh-Hans»] would also match zh-Hans-CN .

Generic class or id selectors

This method avoids the need to match the language declarations at all, and relies on class or id attribute markup. Using an ordinary CSS class or id selector works with most browsers that support CSS. The disadvantage is that adding the attributes takes up time and bandwidth.

For the markup example above, this would require us to change the HTML code by adding class attributes as follows:

We could then have the following styling:

Using CSS selectors in XML with xml:lang

As mentioned earlier, in a document that is parsed as XML you need to use the xml:lang attribute (rather than the lang attribute) to express language information.

Use of :lang is straightforward. If the document is parsed as HTML, the :lang selector will match content where the language was defined using a lang attribute value. However, if the document is parsed as XML, the :lang selector will match content labeled with an xml:lang attribute value and ignore any lang attribute value.

Using attr= and attr|=

Use of these selectors involves some additional considerations.

The xml: part of the xml:lang attribute indicates that this is the lang attribute used in the XML namespace. CSS3 Namespaces describes how to handle xml:lang as an attribute in a namespace. Basically you need to declare the namespace and then replace the colon with a vertical bar. For example:

@namespace xml "http://www.w3.org/XML/1998/namespace" *[xml|lang |= 'ar']
@namespace xml "http://www.w3.org/XML/1998/namespace" *[xml|lang = 'ar']

Any @namespace rules must follow all @charset and @import rules and precede all other non-ignored at-rules and rule sets in a style sheet. Note, also, that the URI for the namespace declaration must be exactly correct.

For browsers that are not namespace aware, you can fall back to escaped characters. For this you need no @namespace declaration, just one of the following:

Note, however, that if you try to use this approach with a namespace-aware browser (ie. most recent, major browsers), it will not work, so if you feel it is needed, you should use this approach in addition to the namespace-based selectors.

By the way

I have used the language codes zh-Hant and zh-Hans . These language codes do not represent specific languages. zh-Hant would indicate Chinese written in Traditional Chinese script. Similarly zh-Hans represents Chinese written in Simplified Chinese script. This could refer to Mandarin or many other Chinese languages.

Until recently the codes zh-TW and zh-CN were used to indicate Traditional and Simplified versions of Chinese writing, respectively. In reality, zh-TW should indicate Chinese spoken in Taiwan, although there is more than one Chinese language spoken in Taiwan. Similarly zh-CN represents Chinese spoken in China (PRC). This could refer to Mandarin or any other Chinese language.

If you need to use language tags to differentiate between Chinese languages, the IANA language subtag registry has more precise language codes for a range of Chinese languages. For more information see Language tags in HTML and XML.

Further reading

Оцените статью