Skip to content

Instantly share code, notes, and snippets.

@krambuhl
Last active June 22, 2018 14:44
Show Gist options
  • Save krambuhl/9dd229f391aceb3012b4 to your computer and use it in GitHub Desktop.
Save krambuhl/9dd229f391aceb3012b4 to your computer and use it in GitHub Desktop.
Sass mixin for creating media queries with min/max arguments
@mixin respond($min: -1, $max: -1, $media: "all") {
$query: "only " + $media;
@if $min != -1 and $max != -1 {
$query: "only " + $media + " and (min-width: " + $min + ") and (max-width: " + ($max - 1) + ")";
} @else if $min == -1 and $max != -1 {
$query: "only " + $media + " and (max-width: " + ($max - 1) + ")";
} @else if $min != -1 and $max == -1 {
$query: "only " + $media + " and (min-width: " + $min + ")";
}
@media #{$query} {
@content;
};
}
@krambuhl
Copy link
Author

krambuhl commented Aug 7, 2014

How to use:

@include respond(-1, 600px) { body { background: red; } }
// ==>@media only screen and (max-width: 599px)
// I subtract 1 from `max-width` to simplify writing 
// multiple media queries that don't overlap 
// There is often a 1px cross over where side by side 
// media queries are active, this should help solve that.

// A  `-1` min argument will remove the `min-width`
// from media query, I often write with a `0` argument
@include respond(0, 600px) { body { background: purple; } }
// ==> @media only screen and (min-width: 0) and (max-width: 599px)

@include respond(600px, 960px) { body { background: purple; } }
// ==> @media only screen and (min-width: 600px) and (max-width: 959px)

@include respond(960px, 1280px) { body { background: blue; } }
// ==> @media only screen and (min-width: 960px) and (max-width: 1179px)

@include respond(1280px) { body { background: green; } }
// == @media only screen and (min-width: 1280px)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment