Skip to content

Instantly share code, notes, and snippets.

@tillsanders
Last active October 7, 2021 08:58
Show Gist options
  • Save tillsanders/b4d0868b64555ed01a09aa5d81c68738 to your computer and use it in GitHub Desktop.
Save tillsanders/b4d0868b64555ed01a09aa5d81c68738 to your computer and use it in GitHub Desktop.
BEMIT SASS Mixin

BEMIT SASS Mixin

This is a method to dynamically generate responsive class names as described in BEMIT: Taking the BEM Naming Convention a Step Further.

Named breakpoints

To get started, we need to define our breakpoints:

$breakpoints: (
    'small':  ( min-width:  700px ),
    'medium': ( min-width: 1000px ),
    'large':  ( min-width: 1200px )
);

Generate media queries for a specific breakpoint

You can use any media query you like! To make use of a specific breakpoint or a list of breakpoints, use @include respond-to():

@mixin respond-to($names: ()) {
    @each $name in $names {
        @if map-has-key($breakpoints, $name) {
            @media #{inspect(map-get($breakpoints, $name))} {
                @content;
            }
        } @else {
            @warn "Unfortunately, no value could be retrieved for `#{$name}`.";
        }
    }
}

Generate responsive classes using BEMIT naming convention

To generate BEMIT classes that respond to a certain breakpoint only (e.g. .test@medium), use @include responsive():

@mixin responsive($names: map-keys($breakpoints)) {
    @content;

    @each $name in $names {
        @if map-has-key($breakpoints, $name) {
            &\@#{$name} {
                @media #{inspect(map-get($breakpoints, $name))} {
                    @content;
                }
            }
        } @else {
            @warn "Unfortunately, no value could be retrieved for `#{$name}`.";
        }
    }
}

Based on https://codepen.io/craigmdennis/post/generate-responsive-bemit-classes-with-sass

Example

Using the above mixins, the following code:

.test {
    @include respond-to(small medium) {
        color: red;
    }

    @include responsive(medium large) {
        color: blue;
    }
}

... would result in this CSS output:

.test {
  color: blue;
}

@media (min-width: 700px) {
  .test {
    color: red;
  }
}

@media (min-width: 1000px) {
  .test {
    color: red;
  }
}

@media (min-width: 1000px) {
  .test\@medium {
    color: blue;
  }
}

@media (min-width: 1200px) {
  .test\@large {
    color: blue;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment