Can anyone explain "em is relative to the font size and % is relative to the parent element" by example?
What is the means of relative to the font size and relative to the parent element?
Can anyone explain "em is relative to the font size and % is relative to the parent element" by example?
What is the means of relative to the font size and relative to the parent element?
Consider if you're defining the height of a box inside another box. If you specify the height at 50%, it will be half as tall as the box it's contained within. if you specify the height in ems instead, its height will depend on the size of the letter m in whatever font you're using, and not be dependent on the size of anything but your text.
Look at this example:
<div id='contain' style='height: 400px'>
<div style='height: 1.5em'>Test 1</div>
<div style='height: 50%'>Test 2</div>
</div>
In Test 1, the height of the box is 150% of the size of the text. If the font size is 10px, the height is 15px. In the second example, the height is 50% of the parent element; in this case, Test 2 is 200px, since #contain
is 400px.
If I remember correctly, if you apply percentage to font-size, it will be mapped the same as em. font-size: 150%
is the same as font-size: 1.5em
(I think).
I find it more useful to use em
for height
or width
. If you use it for width
, then the text won't change wrap points when changing the size of your font (when the user changes font size). It's useful to use it when your page is heavy with text, and having a font size that is too small would cause the page to be too wide. (See this article on Em Widths)
<div style='width: 80em`>Lorem ipsum...</div>