.case1 {
margin-bottom: 10px;
}
.case2 span {
margin-bottom: 10px;
}
<div class="case1">
<span>something</span>
</div>
<div class="case2">
<span>something</span>
</div>
如果按如下方式应用 css,您在屏幕上看到的结果是一样的。那么,这两种方法中哪一种是最佳实践,为什么?
- 谢谢回答。如果它是 p 元素而不是 span 元素,则结果很可能是相同的。这种情况下的最佳做法是什么?
<div>
的和<p>
例如是 Block Level可以占用所有边距的元素。 <span>
不能,因为它是 Inline element仅在水平方向占用边距。
来自 W3 :
Margin properties specify the width of the margin area of a box. The
'margin' shorthand property sets the margin for all four sides while
the other margin properties only set their respective side. These
properties apply to all elements, but vertical margins will not have
any effect on non-replaced inline elements.
可以设置display: inline-block;
在你的 span
使其成为 block 级。
.case1 {
margin-bottom: 10px;
}
.case2 span {
margin-bottom: 10px;
margin-top: 20px; /* margin doesn't work */
color: hotpink;
}
.case3 span {
display: inline-block; /* made it block-level, margin works */
margin-top: 40px;
color: blue;
}
<div class="case1">
<span>something</span>
</div>
<div class="case2">
<span>something</span>
</div>
<div class="case3">
<span>something</span>
</div>