Jacky Jacky - 4 days ago 5
CSS Question

Wrong size when setting size for h1 using em

I have h1 tag, and I tried to set the font-size for this tag using em, but instead of going larger, it became smaller. Below is my code:



h1{
font-size: 1.2em;
}

<div class="container">
<h1>This is a title</h1>
<p>hello this is a paragraph</p>
</div>





As noticed in my code, after removing the 1.2em, it becomes larger again. From my understanding, 1em = the current font size of the page. making 2em should make it double the size. 1.2em should make it a bit bigger, but for me here it's making it smaller. How does em work in this case?

Thanks.

Answer

You are correct regarding the definition, but there is also a default style, and the em is related to the font-size of the parent-element that has a fixed size (or the body element if no other element has fixed size).

Here is an example:

body {
  font-size: 13px;
}
.container h1{
  font-size: 1.2em;
}
.container2 {
  font-size: 20px;
}
.container3 {
  font-size: 0.5em;
}
<div>text - 13px</div>
<h1>title 1 - 26px (default to 2em == 13*2 = 26px)</h1>
<div class="container">
  <h1>This is a title - 15.6px (1.2em == 13*1.2 = 15.6px)</h1>
  <p>hello this is a paragraph - 13px</p>
</div>
<div class="container2">
  <h1>Another title - 40px (parent is 20px, default is 2em, 2*20 == 40px)</h1>
</div>
<div class="container3">
  <h1>3rd title - 13px (parent is 13px*0.5(em) == 6.5, default h1 is 2em, 2*6.5px == 13px)</h1>
</div>

Comments