Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Margin and padding using em

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?

like image 977
Robert Smith Avatar asked Feb 28 '12 22:02

Robert Smith


People also ask

Can you use em for margin?

In CSS, the em unit is a general unit for measuring lengths (for example, page margins and padding around elements). You can use it both horizontally and vertically, and this shocks traditional typographers who have always used the em exclusively for horizontal measurements.

Should I use em or px for padding?

It totally depends on your need. Em should be avoided because it depends on the native browser settings, but if you use px then css of the page will be cross browser compatible.

What is 1em margin?

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.

How many pixels is 1em?

So, by default 1em = 16px, and 2em = 32px.


2 Answers

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

like image 182
BoltClock Avatar answered Oct 24 '22 09:10

BoltClock


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.

like image 11
animuson Avatar answered Oct 24 '22 10:10

animuson