用于管理断点的 Mixin

Avatar of Kitty Giraudel
Kitty Giraudel on

响应式网页设计作品通常存在于多个不同的断点上。管理这些断点并不总是那么容易。使用和更新它们有时会很繁琐。因此需要一个 Mixin 来处理断点配置和使用。

简单版本

首先,你需要一个断点映射,与名称相关联。

$breakpoints: (
  'small':  767px,
  'medium': 992px,
  'large':  1200px
) !default;

然后,Mixin 将使用此映射。

/// Mixin to manage responsive breakpoints
/// @author Kitty Giraudel
/// @param {String} $breakpoint - Breakpoint name
/// @require $breakpoints
@mixin respond-to($breakpoint) {
  // If the key exists in the map
  @if map-has-key($breakpoints, $breakpoint) {
    // Prints a media query based on the value
    @media (min-width: map-get($breakpoints, $breakpoint)) {
      @content;
    }
  }
 
  // If the key doesn't exist in the map
  @else {
    @warn "Unfortunately, no value could be retrieved from `#{$breakpoint}`. "
        + "Available breakpoints are: #{map-keys($breakpoints)}.";
  }
}

用法

.selector {
  color: red;
  
  @include respond-to('small') {
    color: blue;
  }
}

结果

.selector {
  color: red;
}
@media (min-width: 767px) {
  .selector {
    color: blue;
  }
}

高级版本

简单版本只允许使用 min-width 媒体查询。要使用更高级的查询,我们可以稍微调整我们的初始映射和 Mixin。

$breakpoints: (
  'small':  ( min-width:  767px ),
  'medium': ( min-width:  992px ),
  'large':  ( min-width: 1200px )
) !default;
/// Mixin to manage responsive breakpoints
/// @author Kitty Giraudel
/// @param {String} $breakpoint - Breakpoint name
/// @require $breakpoints
@mixin respond-to($breakpoint) {
  // If the key exists in the map
  @if map-has-key($breakpoints, $breakpoint) {
    // Prints a media query based on the value
    @media #{inspect(map-get($breakpoints, $breakpoint))} {
      @content;
    }
  }
 
  // If the key doesn't exist in the map
  @else {
    @warn "Unfortunately, no value could be retrieved from `#{$breakpoint}`. "
        + "Available breakpoints are: #{map-keys($breakpoints)}.";
  }
}

用法

.selector {
  color: red;
  
  @include respond-to('small') {
    color: blue;
  }
}

结果

.selector {
  color: red;
}
@media (min-width: 767px) {
  .selector {
    color: blue;
  }
}