B
B
beastbrook2018-09-27 17:27:18
Sass
beastbrook, 2018-09-27 17:27:18

What is the best way to use @media mixin in Sass?

I started learning Sass and came across a lot of possibilities for organizing code.
Let's say I made a mixin for media expressions:

@mixin mw($width) {
  @media (max-width: $width + 'px') {
    @content
  }
}

And then I use it directly in the navigation component file, like this:
.main-nav {
  padding: 0 20px;
  margin-bottom: 20px;
  
  &__list {
    margin: 0;
    padding: 0;
    list-style: none;
    display: flex;
    
    @include mw(720) {
      flex-direction: column;
      align-items: center;
    } 
  }
  
  &__item {
    margin-right: 15px;
    
    @include mw(720) {
      margin-right: 0;
    }
    
    &:last-child {
      margin-right: 0;
    }
  }
  
  &__link {
    font-size: 20px;
    color: red;
    text-decoration: none;
    
    @include mw(720) {
      font-size: 30px;
      color: pink;
    }
  }
}

Is this generally an adequate approach or no one does this? It is clear that in general everything depends on the agreement in the command, but there may be some common practice, for example, to select all media expressions and keep them in a separate file, say _media.scss.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pushkarev, 2018-09-27
@AXP-dev

// _variables.scss

$breakpoints: (
  'xs': ('(max-width: 576px)'),
  'sm': ('(max-width: 768px)'),
  'md': ('(max-width: 992px)'),
  'lg': ('(max-width: 1199px)'),
);

// _mixins.scss
@mixin respond-to($breakpoint) {
  @if map-has-key($breakpoints, $breakpoint) {
    @media #{inspect(map-get($breakpoints, $breakpoint))} {
      @content;
    }
  } @else {
    @error 'Не указано значение для `#{$breakpoint}`';
  }
}

// Usage
@include respond-to('md') {
  // ...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question