SASS媒体查询混合组合

时间:2019-02-08 14:32:21

标签: css sass

我有一个用于媒体查询的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%;
}

1 个答案:

答案 0 :(得分:0)

不要粗鲁,所以请不要那样做,但这不是简单的混合或灵活。

具有一个变量或一个断点图,以及一个使用这些断点的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

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