Skip to content

Instantly share code, notes, and snippets.

@alexrqs
Last active July 27, 2018 22:40
Show Gist options
  • Save alexrqs/4d5cfc8967287ba13c33b82295707cb5 to your computer and use it in GitHub Desktop.
Save alexrqs/4d5cfc8967287ba13c33b82295707cb5 to your computer and use it in GitHub Desktop.
// Solution 1
// Super short respond to function that allows you to use the same value for
// all breakpoints below the one you are usint
$breakpoints: (
xs: 480px,
s: 768px,
m: 1024px,
l: 1366px,
);
@mixin respond-to($bp) {
@media (max-width: #{map-get($breakpoints, $bp)}) {
@content;
}
}
// Example
// Recomendation: put the bp from bigger to smaller.
body {
@include respond-to(l) {
color: black;
}
@include respond-to(s) {
color: black;
}
}
// Solution 2
// Usual solution for respond to function that allows you to use multiple values
$screen-xs: 480px;
$screen-s: 768px;
$screen-m: 1024px;
$screen-l: 1366px;
@mixin respond-to-one($breakpoint) {
@if $breakpoint == xs {
@media (max-width: #{$screen-xs}) {
@content;
}
}
@else if $breakpoint == s {
@media (min-width: #{$screen-xs + 1}) and (max-width: #{$screen-s}) {
@content;
}
}
@else if $breakpoint == m {
// respond to medium and small
@media (min-width: #{$screen-s + 1}) and (max-width: #{$screen-m}) {
@content;
}
}
@else if $breakpoint == l {
// respond to medium and bigweb
@media (min-width: #{$screen-m + 1}) and (max-width: #{$screen-l}) {
@content;
}
}
@else if $breakpoint == xl {
// respond after biggie
@media (min-width: #{$screen-l + 1}) {
@content;
}
}
}
@mixin respond-to($breakpoints...) {
@each $item in $breakpoints {
@include respond_to_one($item) {
@content;
}
}
}
// Example
// Recomendation: put the attributes from bigger to smaller / left to right
body {
@include respond-to(xl, s, xs ) {
color: black;
}
}
breakpoints = {
mobile: 480px,
tablet: 768px,
desktop: 1024px,
}
respond-to($bp) {
// ask if the hash contains the breakpoints from the parameter
// otherwise use the variable itself that allows 2 different scenarios
// +respond-to(tablet | desktop | mobile)
// +respond-to(600)
@media (max-width: breakpoints[$bp] ? breakpoints[$bp] : ($bp)px) {
{block}
}
}
// To apply responsive rules import the mixins/breakpoints file from styles folder and to use it write `+respond-to( mobile | tablet | desktop)` followed by the block of rules that you want to apply.
// A secondary way to use responsive mixins is just writing the number of pixels for the max-width of the breakpoint `+respond-to(600)` will render `("max-width: 600px")`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment