根据文档:
https://www.w3.org/TR/CSS22/visuren.html#anonymous-block-level
匿名盒子的属性继承自enclosing 非匿名框(例如,在小节下方的示例中 标题为“匿名块框”,用于 DIV 的那个)。非继承 属性有它们的初始值。例如,字体的 匿名框继承自DIV,但边距将为0.
CSS:
p {
display: inline
}
span {
display: block
}
<P style="text-align: center;">
<!--enclosing non-anonymous box -->
This is anonymous text before the SPAN - according to the specification it should inherit the text-align: center; property of p, because p is the enclosing non-anonymous box of this anonymous block box
<SPAN>This is the content of SPAN.</SPAN>
<!-- Only this is centered -->
This is anonymous text after the SPAN - according to the specification it should inherit the text-align: center; property of p, because p is the enclosing non-anonymous box of this anonymous block box
</P>
<!--enclosing non-anonymous box -->
匿名块框不居中,只有
span
。
但我确实评论了这个 CSS:
/* p {
display: inline
}
span {
display: block
} */
看来继承了,匿名块框居中
所以,问题是,规则到底指的是什么?请举个例子帮助我
我很困惑
考虑另一个例子:如果我继续将
display: inline;
应用于p
并测试color: red;
属性,它是继承的,即所有文本都变成红色(包括匿名块框)
混淆可能源于样式规则分布在样式表和标记中。
请注意,当组合
p
的所有样式时,您会得到display: inline; text-align: center;
。想象一下,尝试将 text-align: center;
放在 <em>
标签上:居中对齐甚至意味着什么?
你是对的,在链接的规范中,
p
标签确实得到了内联显示,为了演示内联元素如何在块子元素周围“拆分”。要查看样式是如何继承的,我建议应用边框,正如规范在后续段落中提到的那样:
在导致生成匿名块框的元素上设置的属性仍然适用于该元素的框和内容。例如,如果在上例中的 P 元素上设置了边框,则边框将围绕 C1(在行尾打开)和 C2(在行首打开)绘制。
在以下代码段中查看 div 上清晰的内联 CSS 以及边框示例:
p {
display: inline
}
span {
display: block
}
<div style="display: block; text-align: center;">Block display, centered text</div>
<div style="display: inline; text-align: center;">Inline display, centered text</div>
<hr>
<P style="border: 1px solid red;">
<!--enclosing non-anonymous box -->
This is anonymous text before the SPAN - according to the specification it should inherit the text-align: center; property of p, because p is the enclosing non-anonymous box of this anonymous block box
<SPAN>This is the content of SPAN.</SPAN>
<!-- Only this is centered -->
This is anonymous text after the SPAN - according to the specification it should inherit the text-align: center; property of p, because p is the enclosing non-anonymous box of this anonymous block box
</P>
<!--enclosing non-anonymous box -->