css - 强选择器如何覆盖 id 选择器? id 选择器不是更具体吗?

标签 css css-selectors css-specificity

在下面的代码片段中,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>

最佳答案

您的具体情况是正确的,但选择器仅适用于元素的直接内容。所以 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>

关于css - 强选择器如何覆盖 id 选择器? id 选择器不是更具体吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35000517/

相关文章:

css - 移动菜单和动画内容的棘手 z-index 问题

css 径向进度条增量为 1%

html - 这些CSS行之间有什么区别

html - 如何在保持输入值内的文本不变的情况下删除 html 元素?

javascript - deleteRule CSSKeyframesRule 方法在 IE11 中混淆行为

css - 将 CSS 类用于个别效果 - 意见?

html - CSS 正则表达式 id 选择器与类选择器的性能

html - Joomla 模块 CSS 覆盖

html - 计算选择器的特异性(CSS)

html - Css 忽略类规则