【问题标题】:How Can I Use Multiple @include in SCSS?如何在 SCSS 中使用多个 @include?
【发布时间】:2019-09-16 19:55:04
【问题描述】:

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

.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;
    }
}

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

.section-ptb {
    padding-top: 130px;
    padding-bottom: 130px;
    @include desktop , @include tablet, @include mobole {
        padding-top: 80px;
        padding-bottom: 80px;
    }
}

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

【问题讨论】:

  • scss不支持,只能通过创建另一个mixin来分组

标签: css sass gulp-sass scss-mixins


【解决方案1】:

你可以这样使用:

SCSS

@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
      }
    }
  }
}

用法

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

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

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

// and so on...

【讨论】:

    【解决方案2】:

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

    SCSS

    //  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;
      }
    }
    
    

    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; 
      } 
    }
    
    

    【讨论】:

      猜你喜欢
      • 2021-11-24
      • 2017-03-15
      • 1970-01-01
      • 2021-04-19
      • 2020-08-12
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多