何时在 CSS 中使用边距与内边距
在编写 CSS 时,是否应该使用特定的规则或指南来决定何时使用 margin
以及何时使用 padding
?
When writing CSS, is there a particular rule or guideline that should be used in deciding when to use margin
and when to use padding
?
推荐答案
TL;DR: 默认情况下,我在所有地方都使用边距,除非我有边框或背景并想增加可见框内的空间.
对我来说,内边距和边距之间最大的区别是垂直边距会自动折叠,而内边距不会.
To me, the biggest difference between padding and margin is that vertical margins auto-collapse, and padding doesn't.
考虑两个元素,一个在另一个之上,每个元素都有 1em
的填充.此填充被认为是元素的一部分并且始终被保留.
Consider two elements one above the other each with padding of 1em
. This padding is considered to be part of the element and is always preserved.
所以你最终会得到第一个元素的内容,然后是第一个元素的填充,然后是第二个元素的填充,然后是第二个元素的内容.
So you will end up with the content of the first element, followed by the padding of the first element, followed by the padding of the second, followed by the content of the second element.
因此,两个元素的内容最终会相差 2em
.
Thus the content of the two elements will end up being 2em
apart.
现在将该填充替换为 1em 边距.边距被认为在元素之外,相邻项的边距会重叠.
Now replace that padding with 1em margin. Margins are considered to be outside of the element, and margins of adjacent items will overlap.
所以在这个例子中,你最终会得到第一个元素的内容,然后是组合边距的 1em
,然后是第二个元素的内容.所以这两个元素的内容只相差1em
.
So in this example, you will end up with the content of the first element followed by 1em
of combined margin followed by the content of the second element. So the content of the two elements is only 1em
apart.
当您知道要在元素周围说出 1em
间距时,这将非常有用,而不管它在哪个元素旁边.
This can be really useful when you know that you want to say 1em
of spacing around an element, regardless of what element it is next to.
另外两个很大的区别是填充包含在点击区域和背景颜色/图像中,但不包含边距.
The other two big differences are that padding is included in the click region and background color/image, but not the margin.
div.box > div { height: 50px; width: 50px; border: 1px solid black; text-align: center; }
div.padding > div { padding-top: 20px; }
div.margin > div { margin-top: 20px; }
<h3>Default</h3>
<div class="box">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
<h3>padding-top: 20px</h3>
<div class="box padding">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
<h3>margin-top: 20px; </h3>
<div class="box margin">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
相关文章