SASS example - Media queries with mixins and variables


SASS is popular pre processor style language, It provides variety of features to support DRY principle.

SASS media queries usage

Media query feature is introduced in CSS to apply styles based on screen sizes or media types. @media query is used to declare the different devices in SASS like sass

Media queries are supported in latest css. so every css line of code is valid in SASS Following are the selectors for applying different screen sizes media queries executed in browser at run time, where as SASS rules are executed at compile time to generate CSS styles

Change background-color for different media types

Simple example uses media query for setting background-color various screen sizes

body {
  background-color: red;
}

@media screen and (min-width: 600px) {
  body {
    background-color: blue;
  }
}
@media  (min-width: 1000px) {
  body {
    background-color: black;
  }
}

sass variable in media queries using mixins

 SASS code works at compile time, while as browsers and css codes works with media queries at runtime, So it is very difficult to set variable width dynamically, Instead we can use mixin to which accepts width from the media queries content directives allows to place the content later instead of prediefined.

@mixin changewidth($originwidth) {
        @Contents {
            width: $originwidth;
        }
    }
  @media screen and (max-width: 600px) {
        @include changewidth($originwidth: 400px);
    }
    @media screen and (max-width: 1100px) {
        @include changewidth($originwidth: 970px);
    }
    @media screen and (min-width: 1300px) {
        @include changewidth($originwidth: 1180px);
    }

mixin for margin variable value using media queries 

 Other example of passing variable value for different screens using media queries and mixin with default arguments.

  • defined mixin with default margin value and set the value
  • set margin value using include directive in div tag for default screens
  • change default margin for max width=900px using media queries and include directive tag

@mixin changeMargin($margin: 5px){
  margin: $margin
}
div{
  @include  changeMargin
}

@media screen and (max-width: 900px){
  div{
    @include changeMargin(10px)
  }
}

And generated css code is


div {
  margin: 5px;
}

@media screen and (max-width: 900px) {
  div {
    margin: 10px;
  }
}

Similar Posts