0
0
SASSmarkup~5 mins

Media query mixin patterns in SASS

Choose your learning style9 modes available
Introduction

Media query mixin patterns help you write reusable code to make your website look good on different screen sizes.

You want your website to work well on phones, tablets, and desktops.
You need to change styles like font size or layout based on screen width.
You want to avoid repeating the same media query code in many places.
You want to keep your styles organized and easy to update.
Syntax
SASS
@mixin respond-to($breakpoint) {
  @if $breakpoint == small {
    @media (max-width: 600px) {
      @content;
    }
  } @else if $breakpoint == medium {
    @media (min-width: 601px) and (max-width: 1024px) {
      @content;
    }
  } @else if $breakpoint == large {
    @media (min-width: 1025px) {
      @content;
    }
  }
}

The @mixin defines reusable code blocks.

The @content placeholder inserts styles inside the media query.

Examples
This mixin targets small screens up to 480px wide.
SASS
@mixin respond-to($breakpoint) {
  @if $breakpoint == small {
    @media (max-width: 480px) {
      @content;
    }
  }
}
Use the mixin to change the background color on small screens.
SASS
@include respond-to(small) {
  body {
    background-color: lightblue;
  }
}
This applies flex layout to navigation on large screens.
SASS
@include respond-to(large) {
  nav {
    display: flex;
  }
}
Sample Program

This example changes the background color and font size of the page depending on screen size using the media query mixin.

SASS
@mixin respond-to($breakpoint) {
  @if $breakpoint == small {
    @media (max-width: 600px) {
      @content;
    }
  } @else if $breakpoint == medium {
    @media (min-width: 601px) and (max-width: 1024px) {
      @content;
    }
  } @else if $breakpoint == large {
    @media (min-width: 1025px) {
      @content;
    }
  }
}

body {
  font-family: Arial, sans-serif;
  background-color: white;
  color: black;
}

@include respond-to(small) {
  body {
    background-color: lightyellow;
    font-size: 1.2rem;
  }
}

@include respond-to(medium) {
  body {
    background-color: lightgreen;
    font-size: 1.4rem;
  }
}

@include respond-to(large) {
  body {
    background-color: lightblue;
    font-size: 1.6rem;
  }
}
OutputSuccess
Important Notes

Use meaningful names for breakpoints like small, medium, and large to keep code clear.

Mixins help avoid repeating media query code everywhere.

Test your site on different screen sizes to see the changes.

Summary

Media query mixins make responsive design easier and cleaner.

You write the media query once and reuse it with different styles.

This helps your website look good on phones, tablets, and desktops.