使用 scss 的变量,集合和 mixin ,定义mixin 函数,轻松处理媒介查询

源码

// 定义 map 和 mixin
$breakpoints: (
  'phone': (320px, 480px),
  'pad': (481px, 768px),
  'laptop': (769px, 1920px),
  'desktop': (1921, 3440px),
  'tv': 3441px,
);

@mixin responseTo($breakname) {
  $bp: map-get($breakpoints, $breakname);

  @if type-of($bp) == 'list' {
     @media (min-width: nth($bp, 1)) and (max-width: nth($bp, 2)) {
       @content;
     }
  } @else {
    @media (min-width: $bp) {
      @content;
    }
  }
}

// 这里是业务代码
.header {
  width: 100%;
  @include responseTo('phone') {
    height: 50px;
  }
  @include responseTo('pad') {
    height: 60px;
  }
}

编译后的css:

.header {
  width: 100%;
}
@media (min-width: 320px) and (max-width: 480px) {
  .header {
    height: 50px;
  }
}
@media (min-width: 481px) and (max-width: 768px) {
  .header {
    height: 60px;
  }
}

后话

下次挑战用less 实现同样的功能


today
906 声望41 粉丝