2023-11-10 10:02:13

边距和填充的区别?

在CSS中,边距和填充到底有什么区别?它似乎真的没有多大用处。你能给我举个例子说明区别在哪里(以及为什么知道区别很重要)吗?


当前回答

最简单的定义是; Padding是容器元素边界内的一个空格,margin是容器元素边界外的一个空格。 对于不是容器的元素,填充可能没有多大意义,但空白可以帮助排列它。

其他回答

填充

Padding是一个CSS属性,用于定义元素内容与其边框(如果有边框的话)之间的空间。如果元素周围有边框,则填充将从该边框到出现在该边框中的元素内容之间留出空间。如果元素周围没有边框,那么添加填充对该元素没有任何影响,因为没有边框可以提供空格。

保证金

Margin是一个CSS属性,用于定义元素外部到下一个外部元素的间距。

边距影响有或没有边界的元素。如果一个元素有边框,则margin定义了从这个边框到下一个外部元素的空间。如果元素没有边框,则margin定义从元素内容到下一个外部元素之间的空间。

Padding和Margin的区别

所以边距和填充的区别在于填充处理内部空间,而边距处理下一个外部元素的外部空间。

Padding是内容和边框之间的空间,而margin是边框之外的空间。这是我从谷歌快速搜索中找到的一张图片,它说明了这个想法。

边距和填充之间的一个关键区别在任何答案中都没有提到:点击性和悬停检测

增加填充会增加元素的有效大小。有时我有一个很小的图标,我不想让它看起来更大,但用户仍然需要与该图标进行交互。我增加了图标的填充,让点击和悬停的足迹更大。增加图标的边距不会有同样的效果。

关于这个主题的另一个问题的回答给出了一个例子。

了解边距和填充之间的区别是很好的。据我所知:

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).

边距是框外的空间;填充物是盒子内部的空间。用白色填充很难看出区别,但用彩色填充可以很好地看到。