Reputation: 1957
What is the difference between % and em length values? If containing elements'font-size is 10px, 1em = 10px and so is 100% = 10px. None of the answers in Stackoverflow answers this particular question.
Upvotes: 5
Views: 3597
Reputation: 14992
em
unit is dependent of font-size
.
It can be used for fit sizechanged/zoomed texts.
In the snippet below you can see difference:
let list = document.querySelectorAll('.fs');
let fs = 10;
setInterval(() => {
if (fs > 36) fs = 10;
list.forEach(el => el.style.fontSize = fs+'pt');
fs += 1;
}, 100)
.em {
width: 2em;
background-color: cyan;
}
.perc {
width: 10%;
background-color: pink;
}
<div class="em fs">2em</div>
<div class="perc fs">10%</div>
Upvotes: 4
Reputation: 7766
em
is a relative measure to the current font-size of the element in question. 1em is equal to the current font-size of the element in question.
If you haven't set font size anywhere on the page, then it would be the browser default, which is probably 16px. So by default 1em = 16px. If you were to go and set a font-size of 20px on your body, then 1em = 20px.
%
however does not depend on any specific property. it's reference changes as you apply it on different properties.
See this example:
section{
width:100%;
}
div{
width:50px;
height:50px;
margin:0;
padding:0;
}
.a{
background-color:red;
}
.b{
background-color:blue;
width:2em;
}
.c{
background-color:green;
width:50%;
}
<section>
<div class="a">A</div>
<div class="b">B</div>
<div class="c">C</div>
</section>
Upvotes: 1