当两者都有效时,保证金最高点和保证金最低点之间的CSS最佳做法?

Ben*_*dis 7 html css margin

当您想要为放置在第一个元素之后的元素提供空间时,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)

Gil*_*mbo 5

我会使用: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)

  • 我不是在谈论具有相同边距的 div 列表的特定情况,但第一个除外。我说的是实践。 (2认同)

Ben*_*dis 5

在我看来,margin-top第二个区块是更好的做法。

事实上,第一个 div 不应该关心其他 div,因为它是第一个。

如果第二个被删除,我不应该记得margin-bottom从第一个中删除。


Bra*_*MKJ 5

使用 margin-top 将消除使用下一个同级选择器的需要。它还消除了删除最后一个子项的下边距的需要,以避免在面板或框中使用文本时出现填充差异。


Kai*_*aja 5

由于还没有人提到它,我想补充一点,你可以同时使用两者。这将导致它们通过称为边距折叠的功能融合在一起。在某些情况下,这也可能是最佳实践,因为您可以使用它来声明“该元素下面至少需要这么多空间”。请注意,如果您不小心使用了禁用边距折叠的属性(例如浮动、边框或 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)