CSS 使用 em 的边距和填充

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9490974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 03:08:25  来源:igfitidea点击:

Margin and padding using em

cssmarginem

提问by Robert Smith

When 1em is applied to an element, it takes the default value of the browser (usually, 16px) or the font-size value of its parent, right?. But I noticed that if I use something like margin-top: 1emin a h1element (without using a reset stylesheet, and therefore, h1 is set to font-size: 32px), then 1em is equal to 32px, even if its parent element is set to font-size: 16px.

当 1em 应用于元素时,它采用浏览器的默认值(通常为 16px)或其父元素的 font-size 值,对吗?但我注意到,如果我margin-top: 1emh1元素中使用类似的东西(不使用重置样式表,因此 h1 设置为font-size: 32px),则 1em 等于32px,即使其父元素设置为font-size: 16px

However, using something like font-size: 100%; solves the discrepancy.

但是,使用类似 font-size: 100%; 解决了差异。

What am I missing?

我错过了什么?

采纳答案by BoltClock

When 1em is applied to an element, it takes the default value of the browser (usually, 16px) or the font-size value of its parent, right?

当 1em 应用于元素时,它采用浏览器的默认值(通常为 16px)或其父元素的 font-size 值,对吗?

No, it takes its ownfont-size, computed based on its parent(or the default browser-supplied value). Since the browser-supplied font-sizeof h1is 32 pixels, the resultant margin is 32 pixels.

不,它需要自己的font-size根据其父级(或浏览器提供的默认值)计算。由于浏览器提供font-sizeh1是 32 像素,因此产生的边距是 32 像素。

However, using something like font-size: 100%; solves the discrepancy.

但是,使用类似 font-size: 100%; 解决了差异。

By setting font-size: 100%;or font-size: 1em;on an element, you're telling it to use 100% of the font size of its parent, so setting 1emas a length on anything else will follow that 100%.

通过设置font-size: 100%;font-size: 1em;在一个元素上,你告诉它使用其父元素的字体大小的 100%,因此设置1em为任何其他元素的长度将遵循 100%。

回答by animuson

1emis equal to the font-size of the element in question. So when using it with margins, it will be equivalent to the font-size of the element you're applying the margin too.

1em等于相关元素的字体大小。因此,当将它与边距一起使用时,它也将等同于您应用边距的元素的字体大小。