0

I supposed divs below to have the same width. But they are different, although 10px*10em should be equal 100px, similar like 10px*2em equals 20px.

#container1 {
  font-size: 10px;
}
#paragraph1 {
  font-size: 20px;
  width: 100px;
  background-color: yellow;
}
#container2 {
  font-size: 10px;
}
#paragraph2 {
  font-size: 2em;
  width: 10em;
  background-color: yellow;
}
<div id='container1'>
  <p id='paragraph1'>abc</p>
</div>
<div id='container2'>
  <p id='paragraph2'>abc</p>
</div>
TylerH
  • 20,799
  • 66
  • 75
  • 101
Karol Selak
  • 4,248
  • 6
  • 35
  • 65
  • 1
    A great article about this question: [http://engageinteractive.co.uk/blog/em-vs-rem-vs-px](http://engageinteractive.co.uk/blog/em-vs-rem-vs-px) – Ajay Gupta Aug 08 '17 at 08:20

1 Answers1

0

That was my real problem, but I found answer during writing this question. Reason is simple: em units using for width of element are relative to font-size of their own element, not the parent's. So, as font-size equals 2em, which equals 20px, everything is right, because 20px*10em equals 200px.

When I change width to 5em, it works as it should:

#container1 {
  font-size: 10px;
}
#paragraph1 {
  font-size: 20px;
  width: 100px;
  background-color: yellow;
}
#container2 {
  font-size: 10px;
}
#paragraph2 {
  font-size: 2em;
  width: 5em;
  background-color: yellow;
}
<div id='container1'>
  <p id='paragraph1'>abc</p>
</div>
<div id='container2'>
  <p id='paragraph2'>abc</p>
</div>
Karol Selak
  • 4,248
  • 6
  • 35
  • 65