嵌套 div 未被赋予父级样式,而是使用 * 样式

Nested div not being given parent's style, using * style instead

我不明白为什么最里面嵌套的 div 与 #smaller-size 的大小不同。是直系后裔。是不是因为全局的*样式比较具体?这真的让我的页面大吃一惊。我错过了什么?谢谢!

* { font-size: 15pt; }
#smaller-size { font-size: 0.8em; }
<div>
    This should be the size specified by * (and it is)
    <div id="smaller-size">
        This should be the smaller size (and it is)
        <div>
            This is nested in #smaller-size, so it should also be smaller (but it's not!)
        </div>
    </div>
</div>

对,是因为你的全局*风格。您的嵌套 div 没有 classid,浏览器试图找到第一个适用的样式元素,它是 *.

Is it because the global * style is more specific?

没有。这是因为它匹配元素而 #smaller-size 不匹配。

仅当两个选择器匹配同一元素时,特异性才重要。

如果您没有 * { font-size: 15pt; },那么内部 div 将具有 font-sizedefault100% 的行(即与父元素大小相同)。

您可能应该只在 body 上设置字体大小,让继承来处理其余的事情。虽然有一些陷阱:

  • 表单控件不会默认为 100%,因此您可能希望明确设置 input 元素等的大小
  • 在 Quirks 模式下,默认情况下字体可能不会继承到表格中,因此请确保您有一个触发标准模式的 Doctype
  • pt 是为物理媒体设计的单位。它不会在屏幕上准确呈现。考虑使用不同的单位(如像素)。

“*”选择器的特异性是最低可能的 (0,0,0,0),但它适用于所有适用的元素,因此每个 div 将是:

* { font-size: 15pt; }

当您使用 # 选择器设置新的特异性时:

#smaller-size { font-size: 0.8em; }

只有对应id选择器的元素才会比其他元素有更高的特异性,受*影响,都是。 在此特定元素中创建 (0,1,0,0) 特异性值。 此 ID 仅适用于该特定元素。

例如,如果你建立了类似的东西:

#smaller-size>div { font-size: 0.2em }

那么 id smaller-size 下的所有元素 div 将比仅受 *

影响的元素具有更高的特异性

创建类似的东西:

<div> -- specificity (0,0,0,0) = 0
  <div id="smaller-size"> -- specificity (0,1,0,0) = 100
    <div> -- specificity (0,1,0,1) = 101
    </div>
  </div>
</div>

按照这个逻辑:

* { font-size: 15pt; }
#smaller-size { font-size: 0.8em; }
#smaller-size>div { font-size: 0.7em; }
#smaller-size>.smaller { font-size: 0.6em; }
<div>
    specificity of this element (0,0,0,0) = 0
    <div id="smaller-size">
        specificity of this element (0,1,0,0) = 100
        <div>
            specificity of this element (0,1,0,1) = 101
        </div>
        <div class="smaller">
            specificity of this element (0,1,1,1) = 111
        </div>
        <div class="smaller" style="font-size: 0.5em;">
            specificity of this element (1,1,1,1) = 1111
        </div>
        <p>
            specificity of this element (0,0,0,0) = 0
        </p>
    </div>
</div>

Here 很好 post 解释了特异性的工作原理。