【问题标题】:SASS media query mixin combinationSASS 媒体查询 mixin 组合
【发布时间】:2019-02-08 23:03:13
【问题描述】:

我有一个用于媒体查询的 SASS mixin,效果很好,尤其是在嵌套时,但问题是我似乎无法弄清楚如何编写我的 mixin,以便我可以组合不同的媒体查询。有没有一种方法可以让我的 mixin 保持简单但允许多个组合查询?

例如:

@include media(tablet-p) and media(phone) {
     width: 100%;
}

下面是我当前的 mixin,包括我当前的使用方式。

@mixin media($size) {
    @if $size == laptop {
        @media screen and (min-width:1201px) and (max-width:1440px) {
            @content;
        }
    } @else if $size == tablet-l {
        @media screen and (min-width:1024px) and (max-width:1200px) {
            @content;
        }
    } @else if $size == tablet-p {
        @media screen and (min-width:768px) and (max-width:1023px) {
            @content;
        }
    } @else if $size == phone {
        @media screen and (max-width: 767px) {
            @content;
        }
    }
}

@include media(phone) {
    width: 100%;
}

【问题讨论】:

    标签: css sass


    【解决方案1】:

    不要粗鲁,请不要那样做,但这不是一个简单的混合,也不是灵活的。

    有一个变量或断点映射,以及一个接受这些的 mixin。我首先使用移动设备,所以我总是从移动样式开始,所以我最常用的案例是smallmedium,即min-width。有时你必须使用to-small 等。

    $breakpoints: (
      'to-small'      : ( max-width:  766px ),
      'small'         : ( min-width:  767px ),
      'to-medium'     : ( max-width:  991px ),
      'medium'        : ( min-width:  992px ),
      'to-large'      : ( min-width: 1199px ),
      'large'         : ( min-width: 1200px ),
      'to-x-large'    : ( min-width: 1599px ),
      'x-large'       : ( min-width: 1600px )
    );
    

    混音

    @mixin media($breakpoint) {
      @if map-has-key($breakpoints, $breakpoint) {
        @media #{inspect(map-get($breakpoints, $breakpoint))} {
          @content;
        }
      }
    
      @else {
        @warn "Unfortunately, no value could be retrieved from `#{$breakpoint}`. "
            + "Please make sure it is defined in `$breakpoints` map.";
      }
    }
    

    用法

    .block {
      width: 100%;
    
      // this query will apply from widths larger then 1200px
      // meaning you have the same for mobile and tablet
      @include media('large') {
        width: 25%;
      }
    }
    
    .block {
      width: 100%;
    
      // this query will apply from widths larger then 992px (landscape tablet)
      // meaning you have the same for mobile and tablet portrait
      @include media('medium') {
        width: 25%;
      }
    }
    

    【讨论】:

    • 谢谢!我明白。您可以在示例中使用多个媒体查询来使各种尺寸的宽度变为 25% 吗?
    • 我以前没见过这个,所以我会说不,但我可能是错的。不管怎样,即使有可能,我也永远不想混合媒体查询:)。 @JohnthePainter
    • 为什么不呢?有时,相同的样式适用于手机和平板电脑肖像,否则您必须将所有内容写两次?
    • @JohnthePainter 取决于您如何构建 CSS。让我用一个更好的例子来更新我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    相关资源
    最近更新 更多