在CSS中,边距和填充到底有什么区别?它似乎真的没有多大用处。你能给我举个例子说明区别在哪里(以及为什么知道区别很重要)吗?
当前回答
边距和填充都是填充的类型....一个(margin)在元素边框之外,使其与其他元素保持距离,另一个(padding)在元素内容之外,使内容与元素边框保持距离。
其他回答
自我说明图像
L - Left, R- Right and T - Top, B - Bottom
边距和填充之间的一个关键区别在任何答案中都没有提到:点击性和悬停检测
增加填充会增加元素的有效大小。有时我有一个很小的图标,我不想让它看起来更大,但用户仍然需要与该图标进行交互。我增加了图标的填充,让点击和悬停的足迹更大。增加图标的边距不会有同样的效果。
关于这个主题的另一个问题的回答给出了一个例子。
你可以看看这个链接,在那里你可以看到在CSS中padding和margin是如何工作的。 https://raw.githack.com/sushantbramhacharya/WebTechnology_LEC/main/margin/index.html
填充
Padding是一个CSS属性,用于定义元素内容与其边框(如果有边框的话)之间的空间。如果元素周围有边框,则填充将从该边框到出现在该边框中的元素内容之间留出空间。如果元素周围没有边框,那么添加填充对该元素没有任何影响,因为没有边框可以提供空格。
保证金
Margin是一个CSS属性,用于定义元素外部到下一个外部元素的间距。
边距影响有或没有边界的元素。如果一个元素有边框,则margin定义了从这个边框到下一个外部元素的空间。如果元素没有边框,则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).