Margin and padding using em

谁说胖子不能爱 提交于 2019-12-12 08:18:54

问题


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: 1em in a h1 element (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.

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

What am I missing?


回答1:


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?

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

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

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 1em as a length on anything else will follow that 100%.




回答2:


1em is 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.



来源:https://stackoverflow.com/questions/9490974/margin-and-padding-using-em

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!