Skip to content Skip to sidebar Skip to footer

Can Anyone Explain "em Is Relative To The Font Size And % Is Relative To The Parent Element" By Example?

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 e

Solution 1:

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.

Solution 2:

Look at this example:

<divid='contain'style='height: 400px'><divstyle='height: 1.5em'>Test 1</div><divstyle='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>

Solution 3:

em is a typographic measurement - essentially % of fontsize. while %, as you have said is relative to the parent element.

so lets take:

body {font-size: 12px;}
p.rel-to-font { font-size: 1.5em;}
<body><pclass="rel-to-font"> Some cool text</p></body>

in this example p.rel-to-font will have an effective font-size of 18px. 150% of 12px.

body,p {font-size: 12px;}
div {font-size: 15px;}
p.rel-to-parent { font-size: 150%;}
p.rel-to-font { font-size: 1.5em;}

<body><div><pid="test-1"class="rel-to-parent"> Some cool text</p><pid="test-2"class="rel-to-font"> Some cool text</p></div><pid="test-3"class="rel-to-font"> Some cool text</p><pid="test-4"class="rel-to-parent"> Some cool text</p></body>

in this example #test-1 will have an effective font-size of 22.5px, #test-2 will be 18px, #test-3 will be 18px, and #test-4 will be 18px.

I hoe that helps.. i couldn't really come up with a good example set... In most cases % and em generally work out to the same thing - not always obviously but just most of the time in practical implementations.

Post a Comment for "Can Anyone Explain "em Is Relative To The Font Size And % Is Relative To The Parent Element" By Example?"