Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

css selectors - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...