我正在阅读一本关于 CSS 基础知识的书。书中声称内联元素具有完整的padding属性,但没有margin-top/bottom属性,只有margin-left/right属性。
我的第一个问题是,在哪里可以找到这个官方声明?我找到了 here如果 margin-top/bottom 设置为 auto
则它被设置为 0
。但这与说 margin-top/bottom 不适用于内联元素有什么不同吗?
我的第二个问题是,内联元素真的有完整的填充属性吗?我尝试了以下示例:
<!DOCTYPE html>
<html>
<head> </head>
<body>
<div style="margin: 20px; border: solid 20px;background: red;">
<p style="margin:0">
test test test test test test test test test test test test test test test test test test test test test test test test
<strong style="padding:20px;background-color:yellow">hello</strong> test test test test
</p>
</div>
</body>
</html>
现在,这表明填充实际上以某种方式起作用,但出于某种原因,padding-top
和 padding-bottom
对周围的文本没有影响。这是为什么? W3 标准中是否提到过这一点?
最佳答案
It is claimed in the book that an inline element has complete padding properties but no margin-top/button properties, only margin-left/right properties.
My first question is, where can I find this as an official statement?
你不会,因为这不是真的。在box model它说对于 margin-top 和 margin-bottom:
These properties have no effect on non-replaced inline elements.
但是“没有效果”并不意味着属性不存在。具体来说,它们的存在确实是为了继承。考虑这个例子:
p { border:1px solid red }
i { vertical-align:top; }
span { margin-top: 20px; margin-bottom: 20px; }
b { display:inline-block; }
.two { margin:inherit; }
<p><i>Hello</i> <span>World <b class="one">my good friend</b></span></p>
<p><i>Hello</i> <span>World <b class="two">my good friend</b></span></p>
我们可以看到类为“two”的 b 元素继承了行内非替换 span 元素的 margin top 和 bottom 属性,并且由于 b 元素是 inline-block,margin-top 和 bottom 确实会导致布局差异。如果跨度上不存在 margin-top 和 bottom 属性,那将是不可能的。
关于css - 内联元素的填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33620139/