Skip to content

Instantly share code, notes, and snippets.

@vestman
Created March 10, 2016 08:58
Show Gist options
  • Save vestman/6237abef54322a73f782 to your computer and use it in GitHub Desktop.
Save vestman/6237abef54322a73f782 to your computer and use it in GitHub Desktop.
Less: Mixin for building media queries
//
// Create media queries
// -
// Live example: http://goo.gl/M1pJ6c
// -
// Example:
// .selector {
// ...
// .Mq(sm; {
// width: 100px;
// height: 200px
// });
// }
// Output:
// .selector {
// ...
// }
// @media screen and (min-width: 768px) {
// .selector {
// width: 100px;
// height: 200px;
// }
// }
// -
// Example using max width:
// .selector {
// ...
// .Mq(- sm; {
// width: 100px;
// height: 200px
// });
// }
// Output:
// .selector {
// ...
// }
// @media screen and (max-width: 767px) {
// .selector {
// width: 100px;
// height: 200px;
// }
// }
// -
// Example using both min and max width:
// .selector {
// ...
// .Mq(sm md; {
// width: 100px;
// height: 200px
// });
// }
// Output:
// .selector {
// ...
// }
// @media screen and (min-width: 768px) and (max-width: 991px) {
// .selector {
// width: 100px;
// height: 200px;
// }
// }
//
.Mq(@breakpoints; @rules;) {
// If there's only one breakpoint specified
& when (length(@breakpoints) = 1) {
@query: ~"(min-width: @{breakpoint-@{breakpoints}})";
@media screen and @query {@rules();};
}
// If there's two breakpoints specified
& when (length(@breakpoints) = 2) {
@bpMin: extract(@breakpoints, 1);
@maxVar: extract(@breakpoints, 2);
@tmpMax: ~"breakpoint-@{maxVar}";
@bpMax: (@@tmpMax - 1);
// If the first "breakpoint" = -, then let's build a max-width query
& when (@bpMin = -) {
@query: ~"(max-width: @{bpMax})";
@media screen and @query {@rules();};
}
// If the first breakpoint is something else than "-",
// then let's build a min-width AND max-width query
& when not (@bpMin = -) {
@query: ~"(min-width: @{breakpoint-@{bpMin}}) and (max-width: @{bpMax})";
@media screen and @query {@rules();};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment