Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between % and em?

Tags:

css

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.

like image 716
user7339197 Avatar asked Dec 30 '16 06:12

user7339197


People also ask

What is difference between em and REM?

Basically that both rem and em are scalable and relative units of size, but with em, the unit is relative to the font size of its parent element, while the rem unit is only relative to the root font size of the HTML document. The “r” in rem stands for “root”.

How do you use em?

Use em dashes to set off parenthetical information Em dashes are often used to set off parenthetical information. Using em dashes instead of parentheses puts the focus on the information between the em dashes.

What is difference between REM em and px?

Margin for typography ( rem ) - Case for margin between heading and paragraph. Padding for typography ( em ) - Case for different button size. Font size ( em or % ) - Case for heading font size and secondary font size. Root font size ( px ) - It is the root!


2 Answers

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>
like image 117
vp_arth Avatar answered Sep 21 '22 22:09

vp_arth


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>
like image 20
ab29007 Avatar answered Sep 22 '22 22:09

ab29007