Search code examples
htmlcssmedia-queriesfont-size

Why does media query not change font-size in this example?


I have read through related questions and still not found an answer. I've tried to simplify as much as possible and still get unexpected results.

My media query does not change the font-size of the element, though it will change the color no problem. Can anyone explain this behavior?

eg.

<!DOCTYPE html>
<html>
<head>
<title>DISOBEDIANT HEADER</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>

<style type="text/css">

   @media all and (max-width: 400px) {
        h1 {
            color: blue;
            font-size:26px;
        }
    }

   h1 {
       font-size: 56px;
   }

</style>

</head>
<body>

    <h1>DISOBEDIENT HEADER</h1>

</body>
</html>

Solution

  • You have two rule-sets that change the font size.

    They have identical selectors so are equally specific.

    Therefore the one that is declared last will always be applied.

    So either:

    • The width is more than 400px, so the font size is set to 56px
    • The width is 400px or less, so the font size is set to 26px and then immediately changed to 56px

    Change the order of your rule-sets (or use a more specific selector inside the media query).