在进行媒体查询的编写的时候,我们可以利用scss与与编译器,通过@include混入的方式对代码进行简化,从而大大提高了代码的可维护性,也减少了代码的编写量,废话不多说,直接上代码
css
// 定义设备数值
$breakpoints: (
'phone': (320px, 480px),
'ipad': (481px, 768px),
'notebook': (769px, 1024px),
'pc': 1205px
);
// sass 混合
@mixin respnseTo($breakname) {
// map-get:从对应键值对中获取数据,
$bp: map-get($breakpoints, $breakname);
// 判断 $bp 是 list,还是单个值
@if type-of($bp) == 'list' {
// 从 list 中获取第一项和第二项数据
$min: nth($bp, 1);
$max: nth($bp, 2);
@media (min-width: $min) and (max-width: $max) {
// @content:混入其他的数据
@content;
}
} @else {
@media (min-width: $bp) {
@content;
}
};
}
.container {
width: 100%;
@include respnseTo('phone') {
height: 50px;
}
@include respnseTo('ipad') {
height: 60px;
}
}
最后编译结果:
css
@media (min-width: 320px) and (max-width: 480px) {
.header {
height: 50px;
}
}
@media (min-width: 481px) and (max-width: 768px) {
.header {
height: 60px;
}
}