cssmedia-queriescss-specificitycss-cascade

media-query specificity - why is the largest style used when using max-width media queries?


I have the following (simplified) example code: ( jsbin: http://jsbin.com/cisahilido/1/edit?html,css,output )

SCSS:

.container {
  background: none;
}

@media screen and (max-width: 480px) {
  .container {
    background: red;
  }
}

@media screen and (max-width: 768px) {
    .container {
    background: white;
  }
}

@media screen and (max-width: 1024px) {
    .container {
    background: blue;
  }
}

markup:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div class="container">
    hello!
  </div>
</body>
</html>

Now, when the screen is 480px or less, I would expect the .container to have a red background. However, it seems to ALWAYS have the blue background, up until the 1024px breakpoint, then it is has no background.

Why do max-width styles override smaller breakpoints with bigger ones?


Solution

  • Because 480 is less than the last max-width of 1024. CSS always uses the last valid value, so you need to order max-width media queries from largest to smallest to get the intended value.

    jsbin

    .container {
        background: none;
    }
    
    @media screen and (max-width: 1024px) {
        .container {
            background: blue;
        }
    }
    
    @media screen and (max-width: 768px) {
        .container {
            background: white;
        }
    }
    
    @media screen and (max-width: 480px) {
        .container {
            background: red;
        }
    }