使用 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 實現同樣的功能