Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Do media queries for adaptive design cascade based on order of code in the css?

If I'm browsing a webpage with a smartphone:

@media screen and (max-width: 480px) {
/*code for optimal smartphone styling*/
}
@media screen and (max-width: 1024px) {
/*code for optimal tablet styling*/
}

The browser will first see my smartphone is 480px or less and use the first media query styling. But when it scans below that and sees my smartphone is less than 1024px, will it use the bottom media query instead?

I think the answer is no, but I just puzzled out a yes answer.

2 Answers

John Locke
John Locke
15,479 Points

Richard:

If there are two different selectors with equal specificity in your CSS, the last one to appear will win.

Here's how I advise handling your media queries: If the first part of your style sheet is mobile first, and you are starting with the styles for a 320px screen, then I would arrange your media queries from low to high. MQs -> max-width: 480, max-width: 600, max-width: 768, max-width: 1000, max-width: 1280, min width: 1281

If your regular CSS begins with a desktop layout, then take your Media Queries from high to low.

  MQs -> max-width: 1280, max-width: 1000, max-width: 768, max-width: 600, max-width: 480, max-width: 320

These are for example.

It will use the bottom query.

You're saying the following

  • If the screen has a maximum width of 480px (less than or equal to 480px) do the following styles; if it's higher, I'm not applicable.

*If the screen is less than a maximum width of 1024px do the following styles.

Be careful to have a min-width breakpoint implemented to not leave the user with a confusing size on larger sizes.

Your last breakpoint should probably be for example the following if you only had those two (doubtful, and I know you're just commenting from the challenge):

@media screen and (min-width: 481px) 
  //Code here. Remember,  don't use px units for your breakpoints, use ems. 

If you don't know already beyond the scope of the course, don't use pixels for breakpoints, use ems; pixels are too brittle to changes you can't account for by the user that can lead to unexpected results and sort of nuances somewhat too verbose to mention here.