一般在项目为了适配多种设备,常用的一种方式就是使用媒体查询,比如我们需要给一个卡片在手机、pad、笔记本与电脑中显示不同的宽度,那么代码一般会这样写:
.card {
height: 300px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 4px;
}
/* 手机 */
@media (min-width: 320px) and (max-width: 480px) {
.card {
width: 100%;
}
}
/* 平板 */
@media (min-width: 481px) and (max-width: 768px) {
.card {
width: 50%;
}
}
/* 笔记本 */
@media (min-width: 769px) and (max-width: 1366px) {
.card {
width: 33%;
}
}
/* 电脑 */
@media (min-width: 1367px) {
.card {
width: 400px;
}
}
.header {
height: 50px;
}
@media (min-width: 320px) and (max-width: 480px) {
.header {}
}
/* ... */
如果 css
代码比较少的情况下这种写法没什么问题,但是一旦样式类比较多的情况下维护起来就很繁琐,每个样式类都需要写对应的 @media
min-width
max-width
这种情况下我们可以借助 scss
来统一维护媒体查询的变量与对应设备的宽度。
/* 这里声明有哪些设备以及对应的宽度 */
$screens: (
'phone': (320px, 480px),
'pad': (481px, 768px),
'laptop': (769px, 1366px),
'desktop': (1367px)
)
/* 抽出媒体查询逻辑,传入设备名称,并通过 content 接收具体内容 */
@mixin responseScreen($device) {
/* 通过 map-get 获取对应的设备宽度信息 */
$width: map-get($screens, $device);
@if type-of($width) == 'list' {
@media (min-width: nth($width, 1)) and (max-width: nth($width, 2)) {
@content;
}
} @else {
@media (min-width: $width) {
@content;
}
}
}
.card {
height: 300px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 4px;
/* 使用 */
@include responseScreen('phone') {
width: 100%;
}
@include responseScreen('pad') {
width: 50%;
}
@include responseScreen('laptop') {
width: 33%;
}
@include responseScreen('desktop') {
width: 400px;
}
}
.header {
height: 50px;
/* 使用 */
@include responseScreen('phone') {}
@include responseScreen('pad') {}
@include responseScreen('laptop') {}
@include responseScreen('desktop') {}
}
这样我们就将 $screens
设备的类型与宽度抽出用 map
存放可以单独维护,也将媒体查询处理抽出放到 mixin
混入中,这样如果有修改宽度和媒体查询时,需要更改的代码就会变少。