响应式网页设计作品通常存在于多个不同的断点上。管理这些断点并不总是那么容易。使用和更新它们有时会很繁琐。因此需要一个 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;
}
}
真的很喜欢这个 Mixin,不过我想知道如何在视网膜设备上使用它。是否像添加另一个变量一样简单,还是需要添加一个额外的 if 语句?
非常有帮助,感谢分享!
但是如果我的断点是嵌套的映射键呢?就我所知,‘map-has-key’ 只能在顶层使用,而且我不允许在 Mixin 中放置函数。
映射示例
这是过度设计吗?
@Jack,为什么不将 $structure 变量分成两个不同的变量:$containers 和 $breakpoints 呢?