html - 使用#id 选择器

标签 html css

我主要从 W3Schools 学习了 HTML/CSS 几天。

您能否解释(或提供引用)为什么 div 有黑色背景,而不是橙色?谢谢。

<!DOCTYPE html>
<html>
  <head>
    <style>
      div#hello { background-color: black; }
      div { background-color: orange; }
    </style>
  </head>
  <body>
    <div id="hello" style="height: 50px; width:50px" ></div>
  </body>
</html>

最佳答案

这称为选择器特异性。你的目标是 div#hello,更具体。 div#hello 下面的 div 选择器是一种更通用的样式,但您可以用更具体的 div#hello 样式覆盖 div 样式。

虽然div选择器出现在div#hello样式的下方,但由于特殊性,div#hello选择器被取而代之。

https://css-tricks.com/specifics-on-css-specificity/

关于html - 使用#id 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30879298/

相关文章:

javascript - 我写了一个 JavaScript 在 Canvas : "ฅ(*ΦωΦ*) ฅ" But the cat jumps weirdly 上移动一只猫

javascript - 有没有更好的方法来获取 outerHtml?

html - 不使用 ERB 呈现 HTML 表单

HTML 不会覆盖背景图片

javascript - 单击禁用按钮时添加 CSS

html - 如何将周期性图像作为边框添加到 div

javascript - 防止内容可编辑 div 中的文本选择/突出显示

html - 将文本区域和表单放置在 div 底部会扭曲文本区域的宽度

html - 如何将三个点均匀地间隔为瘦汉堡菜单图标?

html - 缩放 <image> 以适应 <div> 约束 - 最好在没有背景图像的情况下进行