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:

#page-header {
  width: 100%;
  position: fixed;
  border: none;
}

#primary-content{
  width: 70%
  float: left;
}

#sidebar-content {
  width: 70%;
  float: left;
}


//Media Queries
@media (max-width: 767px) {
  .#page-header {
    position: relative;
  }

  #primary-content{
    width: 100%
    float: none;
  }

  #sidebar-content {
    width: 100%;
    float: none;
  }
}

 

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:

#page-header {
  width: 100%;
  position: fixed;
  border: none;
  @include mobile {
    position: realtive;
  }
}

#primary-content{
  width: 70%
  float: left;
  @include mobile {
    float: none;
    width: 100%
  }
}

#sidebar-content {
  width: 70%;
  float: left;
  @include mobile {
    float: none;
    width: 100%
  }
}

Now we break files up by functionality.

header.scss
footer.scss

This is how it’s done.

_variables.scss

$mobile-width: 320px;
$mobile-wide-width: 568px;
$tablet-width: 768px;
$desktop-width: 1024px;

And a file named

** mixins.scss  **

@mixin mobile {
	@media (min-width: 0) and (max-width: #{$tablet-width - 1px}) {
		@content;
	}
}

@mixin desktop {
	@media (min-width: #{$desktop-width}) {
		@content;
	}
}

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 *