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 Sass Basics (retired) Advanced Sass Concepts Working with Media Queries

Bad practise with media Queries

I know this video shows how easy media queries can be done with Sass but the output in css doesn't seem good practise as the media queries is repeated a bunch of times rather than it being in just one media query. Hampton suggests that writing media queries the traditional way isn't helpful but compared to the code that gets compiled in my opinion is seems so. Does anyone else know any other ways of outputting just one media query in your css

2 Answers

Kevin Korte
Kevin Korte
28,148 Points

I write Sass media queries directly where they are needed in the file. I do not output one big media query at the bottom of the page. One of the biggest problems with doing that is your are playing around with specificity, since values at the bottom of the CSS doc holds more weight than anything above it. This can cause frustrating issues.

The browser really doesn't care, that I'm aware of if you have many small media queries or one big on. There might be miliseconds of performance advantages to have one big media query at the bottom. But at the end of the day, does using Sass to output small media queries throughout the CSS file make it more difficult to read? Yeah, possibly. But if you're using Sass, what scenario would you want to read the vanilla CSS file? Plus I minimize the CSS so it's not even readable anyway.

If I enter:

h1 {
    @media (max-width: 480px) {
        background: red;
    }

p {
    @media (max-width: 480px) {
        background: red;
    }

When it's compiled the css will be:

@media (max-width: 480px) {
    h1 {
        background: red;
    }

@media (max-width: 480px) {
    p {
        background: red;
    }

Rather than:

@media (max-width: 480px) {
    h1, p {
        background: red;
    }

Which is almost half the size!

This does seem to produce a large amount of useless code, so you should try and avoid stacking up like this if you have more than 3 occasions, however if you apply some logic you should be able to note what you are applying the same effect to and group these in a separate media query. The great thing is this won't cause any issue to your Sass writing, just pop a media query in as normal!