Skip to content

Instantly share code, notes, and snippets.

@kabilashgit
Created March 20, 2019 11:57
Show Gist options
  • Save kabilashgit/b9e70a92cb0c5955803979c259544562 to your computer and use it in GitHub Desktop.
Save kabilashgit/b9e70a92cb0c5955803979c259544562 to your computer and use it in GitHub Desktop.
media query mixin

/* Author : Manikandan K */

media query mixin

Bootstrap 4 breakpoints and my custom breakpoints

$grid-breakpoints: (
xs: 0,
sm: 575px,
md: 767px,
lg: 991px,
xl: 1199px,
xlm: 1399px,
xxl: 2499px
);

mixin for media query

@mixin breakpoints-min($min) {
  @if (map_has_key($grid-breakpoints, $min)) {
    @media (min-width: #{map-get($grid-breakpoints, $min)}) {
      @content;
    }
  } @else {
    @media (min-width: $min) {
      @content;
    }
  }
}

@mixin breakpoints-max($max) {
  @if (map_has_key($grid-breakpoints, $max)) {
    @media (max-width: #{map-get($grid-breakpoints, $max)}) {
      @content;
    }
  } @else {
    @media (max-width: $max) {
      @content;
    }
  }
}

@mixin breakpoints-min-max($min, $max) {
  $min-v: map_has_key($grid-breakpoints, $min);
  $max-v: map_has_key($grid-breakpoints, $max);

  @if ($min-v == true and $max-v == true) {
    @media(min-width: #{map-get($grid-breakpoints, $min)}) and (max-width: #{map-get($grid-breakpoints, $max)}) {
      @content;
    }
  } @else if ($min-v == true and $max-v == false) {
    @media(min-width: #{map-get($grid-breakpoints, $min)}) and (max-width: #{$max}) {
      @content;
    }
  } @else if ($min-v == false and $max-v == true) {
    @media(min-width: #{$min}) and (max-width: #{map-get($grid-breakpoints, $max)}) {
      @content;
    }
  }
  @else if ($min-v == false and $max-v == false) {
    @media(min-width: #{$min}) and (max-width: #{$max}) {
      @content;
    }
  }
}

usage in scss

/* 
* use an array key from the $grid-breakpoint (xs, sm, md, lg, xl, xlm, xxl) 
* or 
* any value (100px something like that)
*/

@include breakpoints-min-max (lg, 769px) {
    .buttons {
        margin-top: 1em !important;
    }
}
@include breakpoints-min (lg) {
    .buttons {
        margin-top: 1em !important;
    }
}
@include breakpoints-max (lg) {
    .buttons {
        margin-top: 1em !important;
    }
}

output in css

@media (min-width: 991px) and (max-width: 769px) {
    .buttons {
        margin-top: 1em !important;
    }
}
@media (min-width: 991px) {
    .buttons {
        margin-top: 1em !important;
    }
}
@media (max-width: 991px) {
    .buttons {
        margin-top: 1em !important;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment