如何在 SCSS 中使用多个 @include?

Rub*_*ain 4 css sass gulp-sass scss-mixins

我想include在同一个 SCSS 中使用多个。例如:

.section-ptb {
    padding-top: 130px;
    padding-bottom: 130px;
    @include desktop {
        padding-top: 80px;
        padding-bottom: 80px;
    }
    @include tablet {
        padding-top: 80px;
        padding-bottom: 80px;
    }
    @include mobole {
        padding-top: 80px;
        padding-bottom: 80px;
    }
}
Run Code Online (Sandbox Code Playgroud)

经常使用多个@include 很无聊。有任何方法可以减少代码,我想使用:

.section-ptb {
    padding-top: 130px;
    padding-bottom: 130px;
    @include desktop , @include tablet, @include mobole {
        padding-top: 80px;
        padding-bottom: 80px;
    }
}
Run Code Online (Sandbox Code Playgroud)

但它不是有效的 SCSS。请告诉我另一种减少代码的方法。

Ezi*_*cer 11

你可以使用这样的东西:

社会保障体系

@mixin phone {
  @media /*conditions*/ {
    @content
  }
}

@mixin tablet {
  @media /*conditions*/ {
    @content
  }
}

@mixin desktop {
  @media /*conditions*/ {
    @content
  }
}

@mixin media($keys...) {
  @each $key in $keys {
    @if ($key == phone) {
      @include phone {
        @content
      }
    } @else if ($key == tablet) {
      @include tablet {
        @content
      }
    } @else if ($key == desktop) {
      @include desktop {
        @content
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

用法

@include media(phone, tablet, desktop) {
  // your scss code
}

@include media(tablet, desktop) {
  // your scss code
}

@include media(phone) {
  // your scss code
}

// and so on...
Run Code Online (Sandbox Code Playgroud)


Jak*_*b E 8

正如@karthick 所提到的,不支持动态包含(目前)。在您的情况下,我认为有一个 mixin 来处理所有媒体查询是有意义的——例如:

社会保障局

//  map holding breakpoint values
$breakpoints: (
  mobile : 0px, 
  tablet : 680px, 
  desktop: 960px
);

//  mixin to print out media queries (based on map keys passed) 
@mixin media($keys...){
  @each $key in $keys { 
    @media (min-width: map-get($breakpoints, $key)){
      @content
    } 
  }
}



.section-ptb {
  padding-top: 130px;
  padding-bottom: 130px;

  //  pass the key(s) of the media queries you want to print  
  @include media(mobile, tablet, desktop){
    padding-top: 80px;
    padding-bottom: 80px;
  }
}

Run Code Online (Sandbox Code Playgroud)

CSS 输出

.section-ptb {
  padding-top: 130px;
  padding-bottom: 130px; 
}
@media (min-width: 0px) {
  .section-ptb {
    padding-top: 80px;
    padding-bottom: 80px; 
  } 
}
@media (min-width: 680px) {
  .section-ptb {
    padding-top: 80px;
    padding-bottom: 80px; 
  } 
}
@media (min-width: 960px) {
  .section-ptb {
    padding-top: 80px;
    padding-bottom: 80px; 
  } 
}

Run Code Online (Sandbox Code Playgroud)