This is a method to dynamically generate responsive class names as described in BEMIT: Taking the BEM Naming Convention a Step Further.
To get started, we need to define our breakpoints:
$breakpoints: (
'small': ( min-width: 700px ),
'medium': ( min-width: 1000px ),
'large': ( min-width: 1200px )
);
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}`.";
}
}
}
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
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;
}
}