当您想要为放置在第一个元素之后的元素提供空间时,CSS最佳实践是什么?
假设这个HTML
<div class="a-block">lorem</div>
<div class="another-block">ipsum</div>
Run Code Online (Sandbox Code Playgroud)
你应该使用这个CSS吗?
.a-block { margin-bottom: 10px; }
Run Code Online (Sandbox Code Playgroud)
要么
.another-block { margin-top: 10px; }
Run Code Online (Sandbox Code Playgroud)
?
我会使用:nth-child width margin-top
div:not(:first-child) {
margin-top: 10px
}
Run Code Online (Sandbox Code Playgroud)
<div class="a-block">lorem</div>
<div class="another-block">ipsum</div>
<div class="another-block-1">ipsum</div>
<div class="another-block-2">ipsum</div>
Run Code Online (Sandbox Code Playgroud)
在我看来,margin-top
第二个区块是更好的做法。
事实上,第一个 div 不应该关心其他 div,因为它是第一个。
如果第二个被删除,我不应该记得margin-bottom
从第一个中删除。
由于还没有人提到它,我想补充一点,你可以同时使用两者。这将导致它们通过称为边距折叠的功能融合在一起。在某些情况下,这也可能是最佳实践,因为您可以使用它来声明“该元素下面至少需要这么多空间”。请注意,如果您不小心使用了禁用边距折叠的属性(例如浮动、边框或 Flexbox),边距折叠可能会适得其反。
.a-block {
margin-bottom: 10px;
}
.another-block {
margin-top: 10px;
}
div {
background-color: #e0e0e0;
}
.float {
float: left;
clear: both;
width: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<div class="a-block">Only 10px margin</div>
<div class="another-block">between these elements</div>
<hr />
<div class="a-block float">Double margin because</div>
<div class="another-block float">of the float</div>
Run Code Online (Sandbox Code Playgroud)