在CSS中,边距和填充到底有什么区别?它似乎真的没有多大用处。你能给我举个例子说明区别在哪里(以及为什么知道区别很重要)吗?
当前回答
这里的答案中漏掉了一个关键的东西:
上下页边距是可折叠的。
所以如果你在一个元素的底部有一个20px的边距,在下一个元素的顶部有一个30px的边距,两个元素之间的边距将是30px而不是50px。这不适用于左/右边距或填充。
其他回答
最简单的定义是; Padding是容器元素边界内的一个空格,margin是容器元素边界外的一个空格。 对于不是容器的元素,填充可能没有多大意义,但空白可以帮助排列它。
边距应用于元素的外部,从而影响元素与其他元素的距离。
填充应用于元素的内部,从而影响元素的内容距离边框的距离。
此外,使用边距不会影响元素的尺寸,而填充会使元素的尺寸(设置高度+填充),例如,如果你有一个100x100px的div,填充5px,你的div实际上将是105x105px
自我说明图像
L - Left, R- Right and T - Top, B - Bottom
你可以看看这个链接,在那里你可以看到在CSS中padding和margin是如何工作的。 https://raw.githack.com/sushantbramhacharya/WebTechnology_LEC/main/margin/index.html
了解边距和填充之间的区别是很好的。据我所知:
Margin is the outer space of an element, while padding is the inner space of an element. In other words, margin is the space outside of an element's border, while padding is the space inside of its border. You can set auto value to margin. However, it's not allowed for padding. See this. Note: Use margin: auto to center a block element inside its parent horizontally. Also, it's possible to center an element inside a flexbox vertically or horizontally or both, by setting margin to auto. See this. Margin can be any float number, but padding must not be negative. When you style an element, padding will be styled also; but not margin. Margin gets the parent element's style. For example, when you set the background-color property to black, its inner space (i.e. padding) will be black, but not its outer space (i.e. margin).