【问题标题】:How does a strong selector override an id selector? Isn't an id selector considered more specific?强选择器如何覆盖 id 选择器? id 选择器不是被认为更具体吗?
【发布时间】:2016-05-02 05:30:45
【问题描述】:

在下面的sn-p中,strong选择器怎么会覆盖id选择器呢? id 选择器不是被认为更具体,因此具有优先权吗?

<!doctype html>
<html>
  <head>
  <title>Sample document</title>
  <style>
      strong{color:red;}
      #abc {color:blue;}
  </style>
  </head>
  <body>
    <p id="abc">
      <strong>C</strong>ascading
      <strong>S</strong>tyle
      <strong>S</strong>heets
    </p>
  </body>
</html>

【问题讨论】:

  • 没有任何内容被覆盖,因为您的目标是两个不同的元素。这与特异性无关。
  • 谢谢,但是 标签中的字母不也在 p #abc 中吗?
  • 是的,但是强有color:red,它没有color:inherit
  • strong 取代了#abc,因为#abc 样式仅继承 用于&lt;strong&gt; 的内容。是的,#abc 在命名方面更具体,但在渲染&lt;strong&gt; 时,它只是被继承(不如直接样式规则具体)。如果是&lt;strong id="abc"&gt;,那么绝对是正确的,文本是蓝色的。

标签: css css-selectors css-specificity


【解决方案1】:

您在具体方面是正确的,但选择器仅适用于元素的直接内容。因此,strong 元素的文本颜色不同,因为它嵌套更深,p 选择器无法更改这些元素的颜色。因此,如果您确实想更改 #abc 的强元素,您可以这样做

strong { color: red; }

#abc strong {  color: blue; } 

如果您希望 strong 标签文本与 p 文本相同,那么您可以这样做

#abc, #abc strong { color: red; }

strong { color: red; }
#abc strong {  color: blue; }
#def, #def strong { color: red; }
<p id="abc">
  <strong>C</strong>ascading
  <strong>S</strong>tyle
  <strong>S</strong>heets
</p>
<p id="def">
  <strong>ABC</strong>
DEF
</p>

【讨论】:

  • 因为是嵌套的?
  • 是的。在为p 文本指定颜色时,我没有任何意义,然后该标签内的每个元素都会获得该颜色。
猜你喜欢
  • 2012-03-07
  • 2012-02-15
  • 2015-12-28
  • 2013-03-01
  • 2012-02-18
  • 1970-01-01
  • 2018-08-15
  • 2011-10-21
  • 1970-01-01
相关资源
最近更新 更多