基本使用
Scss中的混合允许定义一组 CSS 规则,然后在不同部分重用这些规则
@mixin flex {
display: flex;
justify-content: center;
align-items: center;
}
.box1 {
@include flex;
}
.box2 {
@include flex;
}
与变量不同,混合不仅可以包含样式规则,还可以包含参数
@mixin flex($layout) {
display: flex;
justify-content: $layout;
align-items: $layout;
}
.box1 {
@include flex(start);
}
.box2 {
@include flex(center);
}
支持声明默认参数,使用时也可以指定某参数
@mixin flex($justify-content: center, $align-items: center) {
display: flex;
justify-content: $justify-content;
align-items: $align-items;
}
.box1 {
@include flex;
}
.box2 {
@include flex(space-between, start);
}
.box3 {
@include flex($align-items: start);
}
通过 @content
在混合中动态注入样式
@mixin flex($justify-content: center, $align-items: center) {
display: flex;
justify-content: $justify-content;
align-items: $align-items;
@content;
}
.box1 {
@include flex() {
gap: 20px;
}
}
.box2 {
@include flex(center, start) {
gap: 10px;
}
}
可以使用条件语句
@mixin theme-color($theme) {
@if $theme == "dark" {
background-color: black;
color: white;
} @else if $theme == "light" {
background-color: white;
color: black;
} @else {
background-color: gray;
color: white;
}
}
title {
@include theme-color(dark);
}
示例
媒体查询确定样式
@mixin respondTo($breakname) {
@if$breakname == "phone" {
@media (min-width: 320px) and (max-width: 480px) {
@content;
}
} @else if$breakname == "pad" {
@media (min-width: 481px) and (max-width: 768px) {
@content;
}
}
}
.header {
width: 100%;
@include respondTo("phone") {
height: 50px;
}
@include respondTo("pad") {
height: 60px;
}
}
通过 scss 的 map
和 map-get
优化代码
$breakpoints: (
"phone": (
320px,
480px,
),
"pad": (
481px,
768px,
),
"notebook": (
769px,
1024px,
),
"desktop": (
1025px,
1440px,
),
"tv": 1441px,
);
@mixin respondTo($breakname) {
$bp: map-get($breakpoints, $breakname);
@if type-of($bp) == "list" {
// 从数组中取出min和max
$min: nth($bp, 1);
$max: nth($bp, 2);
@media (min-width: $min) and (max-width: $max) {
@content;
}
} @else {
@media (min-width: $bp) {
@content;
}
}
}
.header {
width: 100%;
@include respondTo("phone") {
height: 50px;
}
@include respondTo("pad") {
height: 60px;
}
}