skip to Main Content

Why font size is different in divs?

<div style="font-size: 30px;">
    <h1>Sample text</h1>
</div>

<div>
    <h1 style="font-size: 30px;">Sample text</h1>
</div>

Why is this happening?

2

Answers


  1. The default value for h1 tag in Chrome is 2em.

    Ems are relative to the font size set in the CSS (parent element).

    So in your second div you are overwriting the 2em value with 30px for the h1 element – font size is now equal to 30px;

    In your first div you set the font-size of the (container) div to 30px, so now 2em is using this as the base font size – computed font size is now equal to 60px.

    <section style="font-size: 15px">
      <div>base font-size: 15px</div>
      <div style="font-size: 3em">this should be 45px (15px x 3em)</div>
    </section>
    Login or Signup to reply.
  2. In the first instance, you changed the font-size of the entire <div>, which effected the <h1> element. In the second instance, you tried to style the <h1>element directly, which had no effect because the inherent <h1> attributes took priority.

    It’s likely that you don’t want to set font-size for the entire <div>, since any other text elements will be styled similarly, negating the use of a heading element. You can target and style the <h1> elements directly using CSS.

    Tip – you should try using rem units instead of px units to help when making your sites responsive.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search