This snipped shows hay to create a SCSS mixin to apply a group of properties as a Media Query, and also when the root element have a particular class.
As an example, imagine that you have a slider component that display 3 items on desktop view, and just 1 on mobile view. You can manage the styles using media queries for the mobile view.
But what happen if you apply the slider on a grid column and then reduce the screen width, to tablet size maybe? The media query will not be triggered yet, but in this particular case you want to active the styles for the mobile view of the slider.
So, in order to do so, we will configure our SCSS mobile styles to be triggered by the media query, AND by a modifier css class on the root element of the component.
Now, is not posible to write a media query and a selector in the same declaration like you can do with selectors (ex.: h1, .title{ //...} ), so
you will need to duplicate the styles declarations, once for the media query, and once for the modifier selector.
This example mixin will allow you to do declare CSS properties a single time in your SCSS code by calling one mixin, and passing it the mediaquery breakpiont, and the root selector to use.
The component root name is .cmp-title, and the modifier selector to enable the mobile view will be .cmp-title--show-mobile.
Note: Please note that you will requiere to declare a
$cmp: &;variable at the root of your component, and pass it to the mixin.
The mixin is called mediaquery-and-selector and can take up to 3 parameters:
- Root selector name. Required.
- Media Query breakpoint. Optional. Default: $sm (768px).
- Mobile view css class name. Optional. Default:
--show-mobile.
$lg: 1200px;
$md: 992px;
$sm: 768px;
$xs: 375px;
@mixin mediaquery-and-selector($cmp, $breakpoint: $sm, $class: '--show-mobile'){
@media only screen and (max-width: $breakpoint - 1) {
@content;
}
@at-root #{$cmp+$class}#{&} { //This will append $class string to what ever the parent selector class name is
@content;
}
}
/*************************/
.cmp-title{
$cmp: &;
h3{
.title{
color: blue;
@include mediaquery-and-selector($cmp){
color: red;
};
}
}
}
.cmp-sidebar{
$cmp: &;
section{
article{
border:1px solid blue;
padding: 1em;
margin: 1em 0;
@include mediaquery-and-selector($cmp, $xs, '--enable-mobile'){
border:1px solid red;
};
}
}
}.cmp-title h3 .title {
color: blue;
}
@media only screen and (max-width: 767px) {
.cmp-title h3 .title {
color: red;
}
}
.cmp-title--show-mobile.cmp-title h3 .title {
color: red;
}
.cmp-sidebar section article {
border: 1px solid blue;
padding: 1em;
margin: 1em 0;
}
@media only screen and (max-width: 374px) {
.cmp-sidebar section article {
border: 1px solid red;
}
}
.cmp-sidebar--enable-mobile.cmp-sidebar section article {
border: 1px solid red;
}