何时在CSS中使用margin和padding [英] When to use margin vs padding in CSS

查看:234
本文介绍了何时在CSS中使用margin和padding的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写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:除非我有边框或背景,并且想要增加可见框内的空间。

TL;DR: By default I use margin everywhere, except when I have a border or background and want to increase the space inside that visible box.

填充和边距之间的最大区别是垂直边距自动合拢,而填充不会。考虑两个元素,一个在另一个之上,填充1em。这个填充被认为是元素的一部分,并且总是被保留。所以你最终会得到第一个元素的内容,然后是第一个元素的填充,接着是第二个元素的填充,接着是第二个元素的内容。因此,两个元素的内容将以2em为间隔。

To me the biggest difference between padding and margin is that vertical margins auto-collapse, and padding doesn't. 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. Thus content of the two elements will end up being 2em apart.

现在用1em边距替换该填充。边距被认为在元素之外,并且相邻项目的边距将重叠。所以在这个例子中,你将得到第一个元素的内容,后面跟着1em的合并边距,然后是第二个元素的内容。所以两个元素的内容只有1em。

Now replace that padding with 1em margin. Margins are considered to be outside of the element, and margins of adjacent items will overlap. 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 say 1em of spacing around an element, regardless of what element it is next to.

另外两个很大的区别是,padding包含在点击区域和背景颜色/图片中,但不包括边距。

The other two big differences is that padding is included in the click region and background color/image, but not the margin.

这篇关于何时在CSS中使用margin和padding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆