Home > Net >  What does it mean for media queries to be placed at the top level of the code?
What does it mean for media queries to be placed at the top level of the code?

Time:01-27

I was looking into MDN Docs for media queries and it says that:

The @media at-rule may be placed at the top level of your code or nested inside any other conditional group at-rule.

Then I tried to test that with the following code:

@media (min-width: 375px) {
    .main {
        border: 5px dashed lightcoral;
    }
}

.main {
    height: 500px;
    border: 5px solid black;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./styles.css">
    <title>Document</title>
</head>
<body>
    <div ></div>
</body>
</html>

It just works when I set the media query after the .main class. I understand this happens due to the cascade flow in the document, but if that, why the docs says to place it at the top level of my css code?

CodePudding user response:

The @media at-rule may be placed at the top level of your code or nested inside any other conditional group at-rule.

Top level code means the code is not nested inside a CSS class. That statement from MDN docs means the media queries can be nested in the class or just at the bottom of the file to ensure cascade flow (Top level).

  •  Tags:  
  • Related