DEV Community

Esmaeil Bahrani Fard
Esmaeil Bahrani Fard

Posted on • Updated on

Responsive Design with SCSS: A Handy and Beautiful Approach

In the ever-evolving world of web development, responsive design has become a crucial aspect of creating user-friendly and accessible websites. SCSS (Sassy CSS) is a powerful extension of CSS that offers enhanced flexibility and organization for styling web pages. In this article, we will explore a handy and beautiful approach to managing responsive design using SCSS.

Breakpoints and the Breakpoints Map:
One of the key elements in responsive design is defining breakpoints, which are specific screen widths where your website's layout and styling need to adapt. In our SCSS approach, we start by defining a breakpoints map. The breakpoints map is a Sass map that associates names (such as xxs, xs, sm, md, lg, xl) with corresponding screen widths.

The breakpoints map is defined as follows:

$breakpoints: (
  xxs: 480px,
  xs: 768px,
  sm: 991px,
  md: 1280px,
  lg: 1920px,
  xl: 5000px
);
Enter fullscreen mode Exit fullscreen mode

Media Queries Mixin:
To handle the responsive behavior, we create a mixin named break that takes a breakpoint name as a parameter. The mixin checks if the provided breakpoint exists in the breakpoints map. If it does, it extracts the maximum width associated with that breakpoint and generates a media query with the provided styles.

The break mixin is defined as follows:

@mixin break($breakpoint) {
  @if map-has-key($breakpoints, $breakpoint) {
    $max-width: map-get($breakpoints, $breakpoint);
    @media screen and (max-width: $max-width) {
      @content;
    }
  } @else {
    @error "Invalid breakpoint: #{$breakpoint}.";
  }
}
Enter fullscreen mode Exit fullscreen mode

Usage Example:
Now let's see how we can use the break mixin in our SCSS styles. Imagine we have an element with the class .my-element, and we want to apply different styles based on different breakpoints.

.my-element {
  @include break(xs) {
    // Styles for extra-small devices
  }

  @include break(sm) {
    // Styles for small devices
  }
}
Enter fullscreen mode Exit fullscreen mode

In the above example, for screen widths smaller than or equal to 600px (xs breakpoint), the styles within the break(xs) block will be applied. Similarly, for screen widths smaller than or equal to 991px (sm breakpoint), the styles within the break(sm) block will be applied.

Conclusion:
With the handy and beautiful SCSS code provided in this article, managing responsive design becomes more organized and efficient. By defining breakpoints and utilizing the break mixin, you can easily adapt your website's layout and styles to different screen sizes. SCSS empowers developers to create responsive designs with ease, providing a better user experience across various devices.

Download scss source:
For easier access to the entire source code, you can download it from the gist on GitHub.

Top comments (0)