Jake Paris

Breakpoint Helper with SASS/SCSS

When I’m building a new site, I usually spend a fair amount of time showing and hiding things at various breakpoints.

This code defines the major breakpoints in use, then prints out a bunch of helper classes to make the showing/hiding easier.

First create a sass map of all the breakpoints.

$breakpoints: (
	small:550px,
	medium:800px,
	large:1024px
);

Then loop through them and spit out the classes in media queries.

@each $val in map-values($breakpoints) {
		
	// Remove the units. Not strictly necessary, but it
	// makes the class names less unweildy
	// @see http://stackoverflow.com/a/12335841/362769
	$num: $val / ($val * 0 + 1);
	
	@media(min-width: $val){
		.hide-#{$num}-up { display: none; }
	}
	@media(max-width: $val - 1 ) {
		.show-#{$num}-up { display: none; }
	}
}

So the utility hereis that you now have at your disposal a number of utility classes. For instance, an element with the .show-large-up class will only be visible at the “large” breakpoint and up (1024px in this case). Similarly, elements with .hide-medium class will only be visible from 0px to the medium breakpoint (800px in this case).

Incidentally, you can then use the breakpoint map in other places in your file like so:

@media ( min-width: map-get($breakpoints,medium) ) {
	// styles
}

This makes good use of the DRY advantages of SASS so that our major breakpoints are only defined once in the sheet and automatically build out a bunch of helper classes.

2 comments

Leave a Reply