第 7 / 105 道7 / 105 · #272
margin vs padding
Margin vs Padding
先自己答,再往下看Answer it yourself first
一句话:padding 在边框里面, 是「内容和边框的距离」;margin 在边框外面,是「这个盒子和别人的距离」。
实际选哪个,看三条:
- 要不要背景色 / 点击区。padding 属于元素本身,会被背景色覆盖、点它算点到元素; margin 是空白,点不到。按钮想加大点击区一定用 padding。
- 会不会折叠。margin 会上下折叠,padding 永远不会。 想要「稳定的 20px 间距」用 padding 更可控。
- 负值。margin 可以是负数(常用来做重叠、抵消父级 padding), padding 不行。
会追问:「margin: 0 auto 为什么能居中,padding: auto 为什么不行?」—— margin 的 auto 会吃掉剩余空间并平分, padding 根本不支持 auto。 而且这招只对设了宽度的块级元素有效。
In one line: padding is inside the border — the gap between content and border; margin is outside — the gap between this box and everything else.
Three things decide which one you reach for:
- Background and hit area. Padding belongs to the element, so the background paints over it and clicks on it count as clicks on the element; margin is empty space you cannot click. Always use padding to enlarge a button’s hit area.
- Collapsing. Vertical margins collapse; padding never does. For a dependable 20px gap, padding is more predictable.
- Negative values. Margin can be negative (used for overlaps, or to cancel a parent’s padding); padding cannot.
Follow-up: “Why does margin: 0 auto centre something when padding: auto does nothing?” —auto margins absorb the leftover space and split it evenly; padding does not support auto at all. And the trick only works on a block element with a set width.
这道题的出处:Comes from: 课程里的这一节 →this lesson →用抽认卡过一遍Run a flashcard round