Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sass for media queries
$mq-min-width-mobile: null;
$mq-min-width-tablet: 768px;
$mq-min-width-desktop: 992px;
$mq-min-breakpoints: (
mobile: $mq-min-width-mobile,
tablet: $mq-min-width-tablet,
desktop: $mq-min-width-desktop
);
$mq-max-width-mobile: $mq-min-width-tablet - 1px;
$mq-max-width-tablet: $mq-min-width-desktop - 1px;
$mq-max-width-desktop: null;
$mq-max-breakpoints: (
mobile: $mq-max-width-mobile,
tablet: $mq-max-width-tablet,
desktop: $mq-max-width-desktop
);
@function mq-get-breakpoint($name, $breakpoints) {
@if map-has-key($breakpoints, $name) {
@return map-get($breakpoints, $name);
} @else {
@error "Invalid argument: #{$name}.";
}
}
@function mq-get-media-query($min-name: null, $max-name: null) {
$min-width: null;
$max-width: null;
@if $min-name {
$min-width: mq-get-breakpoint($min-name, $mq-min-breakpoints);
}
@if $max-name {
$max-width: mq-get-breakpoint($max-name, $mq-max-breakpoints);
}
@if $min-width and $max-width {
@if $min-width < $max-width {
@return "screen and (min-width: #{$min-width}) and (max-width: #{$max-width})";
} @else {
@error "Invalid arguments: $min-name is greater than $max-name.";
}
} @else if $min-width {
@return "screen and (min-width: #{$min-width})";
} @else if $max-width {
@return "screen and (max-width: #{$max-width})";
} @else {
@error "Invalid arguments: $min-name and $max-name are both null.";
}
}
@mixin mq($min-name, $max-name: null) {
$media-query: mq-get-media-query($min-name, $max-name);
@if $media-query {
@media #{$media-query} {
@content;
}
} @else {
@content;
}
}
.foo {
color: red;
@include mq(tablet) {
color: green;
}
@include mq(desktop) {
color: blue;
}
}
.bar {
@include mq(null, mobile) {
color: red;
}
@include mq(tablet, tablet) {
color: green;
}
@include mq(desktop) {
color: blue;
}
}
// output
.foo {
color: red;
}
@media screen and (min-width: 768px) {
.foo {
color: green;
}
}
@media screen and (min-width: 992px) {
.foo {
color: blue;
}
}
@media screen and (max-width: 767px) {
.bar {
color: red;
}
}
@media screen and (min-width: 768px) and (max-width: 991px) {
.bar {
color: green;
}
}
@media screen and (min-width: 992px) {
.bar {
color: blue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.