CSS Specificity and Inheritance
Given the following code:
* {
font-size: 18px;
}
.container {
font-size: 50%;
}
<div class="container">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate explicabo fugiat laborum minus ullam? Amet delectus facilis id quam temporibus.
</p>
</div>
The result is that the <p>
tag has 18px font-size applied.
But shouldn't every element that is inside of the div container inherit the font-size I apply to it?
Regardless of the *
selector applying the font-size to the <p>
tag,
because a tag is only worth 1 point and a class is worth 10 points?
The .container
rule doesn't match the p
element. So specificity is irrelevant here. Inheritance and specificity are separate concepts and the only time they interact is when more specific/less specific rules contain declarations with inherit
. That is not the case here.
As far as the p
element is concerned, only the *
rule applies, and the *
contains its own font-size
declaration, and so the specified font size follows that declaration.
If the *
rule didn't have its own font-size
declaration, then the p
element would inherit from .container
.
If you want descendants of .container
to take after its font size, you will need an additional .container *
rule. Be very careful with the inherit
keyword when it comes to relative values, though — you probably meant to keep all descendants the same size, so 1em
or 100%
is more appropriate here than inherit
:
* {
font-size: 18px;
}
.container {
font-size: 50%;
}
.container * {
font-size: 1em;
}
<div class="container">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate explicabo fugiat laborum minus ullam? Amet delectus facilis id quam temporibus.
</p>
</div>