Tom
Tom

Reputation: 3627

CSS and how media queries are applied

Suppose I have

/*
css for elements section #1 in page
css for elements section #2 in page
*/

@media screen and (max-width: 960px) {
/* redefines/alters CSS for elements in section #1 in page */
}

@media screen and (max-width: 700px) {
/* redefines/alters CSS for elements in section #2 in page */
}

I have read multiple places that it is always only one media query that is matched... And therefore one can not rely on the CSS already defined for @media screen and (max-width: 960px) will be applied first before @media screen and (max-width: 700px)

However in my tests when resizing a browser window down, I can see @media screen and (max-width: 960px) being applied first. Then I size the window even smaller I can see the changes are kept/combined when @media screen and (max-width: 700px) gets applied

So my question is... Is what I am seeing pure luck and against the specification? Or am I missing something?

Upvotes: 1

Views: 1144

Answers (3)

Chad
Chad

Reputation: 490

I don't think you're understanding the point of the media query itself. Your first 960 declaration says, "if your screen resolution is less than 960px then apply these styles" and then once it hits 700 it will apply those styles. That's just basic responsive design.

Upvotes: 0

dc5
dc5

Reputation: 12441

With media queries, source order matters.

See Logic in Media Queries

In your case, the first query will always match when width <= 960px.

If you want to exclude that css you could add a min-width value to it.

Upvotes: 2

Michael Irigoyen
Michael Irigoyen

Reputation: 22947

Your tests prove true how it should work.

In your example, when the width of the browser is less than 960px and less than 700px, both queries would be considered to be true. That is working as intended and, in fact, is how I've implemented responsive design on several sites, each query being a new breakpoint of how things degrade gracefully into a small form factor.

Upvotes: 3

Related Questions