CSS继承与CSS特异性

问题描述 投票:0回答:1

我在大学计算机科学系的Web开发班上,老师问班级为什么要通过简单的段落标签调用班级(请参见示例代码)。我回答说是因为CSS特殊性,所以我被告知我错了。他想要的答案是因为CSS继承。

虽然是正确的,但为什么CSS特异性是错误的答案?

p {
   color: red;
}

.section {
   color: green;
}
<p class="section">Section</p> 
css inheritance css-specificity
1个回答
0
投票

.container {
  font-size: 35px;
}

p {
  color: red;
}

.section {
  color: green;
}

div.section {
  /* More specific then .section rule */
  color: purple;
}
<div class="container">
  <p>Example of inheritance. This paragraph has inherited the font-size of its parent. <span>This span also inherited font-size.</span></p>
</div>

<div>
  <p class="section">Example of specificity. The "section" class is more specific than the rule created for the p element. Therefore, styles defioned in the "section" class rule may override those defined in the p element rule
  </p>
  <p>No class applied.</p>
  <div class="section">The "div.section" rule is more specific than the ".section" rule, so this text is purple.</div>
</div>

0
投票

这是一个快速的结构示例,可能有助于解释一些;

  1. 此分类将针对浏览器默认样式的初始替代设置为ALL p元素。

p { color: red; }

  1. 此人现在继承了以前为p声明的所有内容,并且将覆盖您指定的属性,但只限于使用此特定类的p元素。

.section { color: green; }

  1. 现在,如果我们想使用特异性来定位此组合的特定实例,我们会做类似的事情;

p[class=section] { color: blue; }

以及一些上下文示例,希望能有所帮助;

p { color: red; }


.section { color: green; }


p[class=section] { color: blue; }
<p>Words Words Words</p>

<p class="section">Words Words Words</p>

<div class="section">Words Words Words</div>

<p class="nothing">words Words Words</p><br/>
© www.soinside.com 2019 - 2024. All rights reserved.