CSS isn't my expertise so there must be something simple I'm misunderstanding. My website allows a person to switch between English and a LTR language. I want by default all text in English to be one font, and all the text from the other language to be a different font. One will be left aligned one will be right aligned. I found the :lang
selector to be a way to implement this, so my CSS looks like:
:lang(en) {
text-align: left;
font: 400 13px/1.25 Verdana, sans-serif;
}
:lang(he) {
text-align: right;
font: 400 13px/1.25 'Alef', sans-serif;
}
This makes both languages have a default font-weight
of 400.
Now, this is the way I set up my HTML:
<!DOCTYPE html>
<html>
<head>...</head>
<body lang="he">
<b>Text here</b>. Hello.
</body>
</html>
I intend to change the lang attribute of <body>
using javascript. Now, as I expected, the text is right-aligned, since I set the lang
to be he
. However, none of the text is bolded. When I use the Chrome element inspector tool, it tells me the following:
:lang(he) { <style>
text-align: right;
font: 400 16px/1.25 "Alef", sans-serif;
}
b { user agent stylesheet
font-weight: bold;
}
The font-weight: bold is crossed out (I don't know how to format within HTML blocks). This indicates to me that the font-weight
set by my :lang {}
is overriding for some reason the default behavior of <b></b>
. Why is this happening? How can I fix it?
Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.
In the case of selectors with equal specificity, the last declaration found in the CSS is applied to the element.
In your case with :lang(he)
you are targeting all the elements with lang-attribute as he
. since your lang attribute is on the body your b
tag also got selected with :lang(he)
.
Now as per the specificity rule b
tag will have the values which you have provided with :lang(he)
as it defined last overriding the default declaration of b
tag.
The solution for your case is instead of selecting all
elements with :lang(he)
select all class with :lang(he)
:
.body:lang(en) {
text-align: left;
font: 400 13px/1.25 Verdana, sans-serif;
}
.body:lang(he) {
text-align: right;
font: 400 13px/1.25 'Alef', sans-serif;
}
<!DOCTYPE html>
<html>
<head>...</head>
<body class="body" lang="he">
<b>Text here</b>. Hello.
</body>
</html>
The other thing you can do is only select a particular element with lang attribute = he, and scope the style to that element:
body:lang(en) {
text-align: left;
font: 400 13px/1.25 Verdana, sans-serif;
}
body:lang(he) {
text-align: right;
font: 400 13px/1.25 'Alef', sans-serif;
}
<!DOCTYPE html>
<html>
<head>...</head>
<body lang="he">
<b>Text here</b>. Hello.
</body>
</html>
You can read about specificity here