何时在 CSS 中使用边距与填充 [英] When to use margin vs padding in CSS

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

问题描述

在编写 CSS 时,是否应该使用特定的规则或指南来决定何时使用 margin 以及何时使用 padding?

解决方案

TL;DR: 默认情况下我到处都使用边距,除非我有边框或背景并且想要增加可见框内的空间.

对我来说,padding 和 margin 的最大区别是垂直边距会自动折叠,而 padding 不会.

考虑两个元素一个在另一个之上,每个元素都有 1em 的填充.此填充被视为元素的一部分并始终保留.

所以你最终会得到第一个元素的内容,然后是第一个元素的填充,然后是第二个元素的填充,然后是第二个元素的内容.

因此这两个元素的内容最终会被 2em 分开.

现在用 1em 边距替换该填充.边距被认为在元素之外,相邻项目的边距会重叠.

所以在这个例子中,你将得到第一个元素的内容,然后是 1em 的组合边距,然后是第二个元素的内容.所以这两个元素的内容仅相差1em.

当您知道要在元素周围说 1em 间距时,这非常有用,而不管它旁边是什么元素.

另外两个很大的区别是填充包含在点击区域和背景颜色/图像中,但不包含边距.

div.box >div { 高度:50 像素;宽度:50px;边框:1px纯黑色;文本对齐:居中;}div.padding >div { padding-top: 20px;}div.margin >div { margin-top: 20px;}

默认

<div class="box"><div>A</div><div>B</div><div>C</div>

<h3>padding-top: 20px</h3><div class="box padding"><div>A</div><div>B</div><div>C</div>

<h3>margin-top: 20px;<div class="box margin"><div>A</div><div>B</div><div>C</div>

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: By default I use margin everywhere, except when I have a border or background and want to increase the space inside that visible box.

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 the content of the two elements will end up being 2em apart.

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.

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>

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆