Search code examples
cssfont-sizecss-specificity

Overridden CSS property can still be used to determine actual value?


In my browser, without any author or user styles, the h1 font-size is 32px. I have been trying to figure out how the h1 font-size results in an actual value of 24px, with the following HTML and CSS.

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Stuff</title>
    <link rel="stylesheet" type="text/css" href="three.css">
</head>
<body>
    <p>My paragraph</p>
    <h1>My H1</h1>
</body>
</html>

CSS:

html {
   font-size: 12px;
}

It looks like the user-agent font-size of 2em overrides the 12px specified in the CSS. Even though it is shown as struck-through in Chrome Dev Tools (see below), it seems the 12px value is also used, because the h1 not the default 32px. How can the 12px be overridden and still be used?

enter image description here


Solution

  • This is called specifity. The selector h1 is more specific than the html selector for the title tag. It has more priority that's why it's overriding your specified style.

    Why having 24px ?

    font-size:2em means twice the font size specified in the parent element (and here it's 12px) so you will have 2*12px = 24px. This is why the 12px you specified is also used.

    To be more generic in the explanation we can say that Xem means X times the size of the current font. The current font depend of course on all the styles you applied (here you only have the one specified in the html tag).

    You can read more here


    If you want to override the style you can simply specify :

    h1 {
      font-size:12px;
    }
    

    or use !important selector like this :

    html {
      font-size:12px!important;
    }