【发布时间】:2021-01-11 12:57:31
【问题描述】:
我现在正在学习在线 Web 开发课程,并且一直在构建一些网页来学习 HTML 和 CSS。在这个特别。我的问题是,在页面中,我的 p 和 h3 元素类型样式规则中的字体系列规则正在覆盖来自特定 ID 选择器的字体系列规则。我能够通过链接选择器来解决这个问题,但我不明白为什么会发生这种情况。
这是我尝试格式化的 HTML 的一部分:
h3 {
font-family: Helvetica, sans-serif;
font-size: 24px;
}
p {
font-family: "Roboto", sans-serif;
}
.font-container {
display: inline-block;
width: 45%;
}
.caps {
text-transform: uppercase;
}
#helvetica{
font-family: Helvetica, sans-serif;
}
#roboto{
font-family: "Roboto", sans-serif;
}
#lora{
font-family: "Lora", serif;
}
<div class="container">
<h2>Fonts</h2>
<div class="font-container" id="helvetica">
<h3>Helvetica</h3>
<div class="normal">
<p>The quick brown fox jumps over the lazy dog.</p>
<p><em>The quick brown fox jumps over the lazy dog.</em></p>
<p><strong>The quick brown fox jumps over the lazy dog.</strong></p>
</div>
<div class="caps">
<p>The quick brown fox jumps over the lazy dog.</p>
<p><em>The quick brown fox jumps over the lazy dog.</em></p>
<p><strong>The quick brown fox jumps over the lazy dog.</strong></p>
</div>
</div>
<div class="font-container" id="roboto">
<h3>Roboto</h3>
<div class="normal">
<p>The quick brown fox jumps over the lazy dog.</p>
<p><em>The quick brown fox jumps over the lazy dog.</em></p>
<p><strong>The quick brown fox jumps over the lazy dog.</strong></p>
</div>
<div class="caps">
<p>The quick brown fox jumps over the lazy dog.</p>
<p><em>The quick brown fox jumps over the lazy dog.</em></p>
<p><strong>The quick brown fox jumps over the lazy dog.</strong></p>
</div>
</div>
<div class="font-container" id="lora">
<h3>Lora</h3>
<div class="normal">
<p>The quick brown fox jumps over the lazy dog.</p>
<p><em>The quick brown fox jumps over the lazy dog.</em></p>
<p><strong>The quick brown fox jumps over the lazy dog.</strong></p>
</div>
<div class="caps">
<p>The quick brown fox jumps over the lazy dog.</p>
<p><em>The quick brown fox jumps over the lazy dog.</em></p>
<p><strong>The quick brown fox jumps over the lazy dog.</strong></p>
</div>
</div>
使用 Chrome DevTools 检查表明该 div 中所有文本的字体系列都继承自 p 和 h3 规则。有人可以解释为什么会这样吗?
【问题讨论】:
-
当您在父元素上设置规则时(
<div id="...">') you are relying on the fact that the children will use theinherit` 值。直接在<h3>元素上设置值将覆盖该inherit值,并且父元素上的规则将在这里放松它的影响。