Better Organization with Sass Media Queries

Using media queries can get confusing and overlapping especially when structure is lacking. With sass css compiler and mixins we can structure our media queries and use them far more elegantly.

Example of CSS alone:

 

Due to CSS structuring, we have to place our media queries away from the code, and it becomes harder and harder to read when you have many break points.

I once worked on a large project that had over 10 different types of page templates. Each page had to be fully responsive and support IE8+. This became a nightmare because we divided our css by breakpoints.

We ended up with all the different files in their respective folder, which looked something like this.

–header (folder)
— mobile.scss
— tablet.scss
— desktop.scss
— desktop-wide.scss

–footer (folder)
— mobile.scss
— tablet.scss
— desktop.scss
— desktop-wide.scss

I’ll stop here…

It became very difficult to adjust code, and difficult to see all the styles affecting elements.  A new developer to the project would be very overwhelmed and just add yet another media query, or override the old code. This made our css code base gigantic.

Alas! There is a better way!

With the power of sass and mixins our previous example becomes:

Now we break files up by functionality.

header.scss
footer.scss

This is how it’s done.

And a file named

This enables you to define your media queries and widths in one place. You can easily change them later without needing to do a find replace for your entire code base.

Also your developers will be happy since all the code for a functionality is found in one place.

Leave a Reply

Your email address will not be published. Required fields are marked *