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?
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
The default value for
h1
tag in Chrome is2em
.So in your second
div
you are overwriting the2em
value with30px
for theh1
element – font size is now equal to30px
;In your first
div
you set the font-size of the (container) div to30px
, so now2em
is using this as the base font size – computed font size is now equal to60px
.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.