在CSS中,边距和填充到底有什么区别?它似乎真的没有多大用处。你能给我举个例子说明区别在哪里(以及为什么知道区别很重要)吗?
当前回答
了解边距和填充之间的区别是很好的。据我所知:
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).
其他回答
边距应用于元素的外部,从而影响元素与其他元素的距离。
填充应用于元素的内部,从而影响元素的内容距离边框的距离。
此外,使用边距不会影响元素的尺寸,而填充会使元素的尺寸(设置高度+填充),例如,如果你有一个100x100px的div,填充5px,你的div实际上将是105x105px
边距是框外的空间;填充物是盒子内部的空间。用白色填充很难看出区别,但用彩色填充可以很好地看到。
基本上,边距和边距的区别在于背景。填充将决定内容之间的空间,而边距将决定元素的外部边缘!
我对边距和填充的理解来自于谷歌的开发人员工具,如图所示
简单来说,边距是指元素周围的空间,padding指元素和元素内内容之间的空间。 这两种方法都用来制造间隙,但方式不同。
使用Margin创建间隙:
在创建间隙时,边缘将相邻的元素推开
使用Padding创建间隙:
使用填充来创建间隙既可以增加元素的大小,也可以缩小其中的内容
为什么知道两者的区别很重要?
了解它们的区别是很重要的,这样你就可以知道什么时候使用它们,并适当地使用它们。
同样值得注意的是,在设计网站布局时,页边距和填充很方便,因为页边距指定了一个元素是向上还是向下,向左还是向右移动,而填充指定了一个元素在容器内的外观和位置。
边距应用于元素的外部,从而影响元素与其他元素的距离。
填充应用于元素内部,因此影响元素内容与边框的距离。
此外,使用边距不会影响元素的尺寸,而填充会使元素的尺寸(设置高度+填充),例如,如果你有一个100x100px的div和5px的填充,你的div实际上将是105x105px