强选择器如何覆盖id选择器?不是一个被认为更具体的id选择器吗?

时间:2016-01-25 19:15:53

标签: css css-selectors css-specificity

在以下代码段中,选择器如何覆盖 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>

1 个答案:

答案 0 :(得分:3)

具有特异性是正确的,但选择器仅适用于元素的直接内容。因此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>

相关问题