问题
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?
回答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.
回答2:
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>
回答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>
<p class="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>
<p id="test-1"class="rel-to-parent"> Some cool text</p>
<p id="test-2" class="rel-to-font"> Some cool text</p>
</div>
<p id="test-3" class="rel-to-font"> Some cool text</p>
<p id="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.
来源:https://stackoverflow.com/questions/2177923/can-anyone-explain-em-is-relative-to-the-font-size-and-is-relative-to-the-par