Mixin
understand:
A 'variable' containing multiple styles, if the defined mix is not used, it will not be parsed into the css style; after use, when parsing, it is equivalent to copying the defined style to the location where it is used.
advantage:
Parameters can be passed.
shortcoming:
Because the code is copied during parsing, there will be a lot of code after parsing.
Basic use:
定义混合:
@mixin mixin-name() {
/* css 声明 */
}
使用混合:
body{
@include mixin-name();
...
}
解析格式:
body{
/* css 声明 */
}
Mix with parameters:
// 定义
@mixin row($dir, $main){
display: flex;
flex-direction: $dir;
justify-content: $main
}
// 调用
.body{
@include row(row, space-between);
}
// 解析
.body{
display: flex;
flex-direction: row;
justify-content: space-between;
}
However, if the parameters are defined, the parameters must be passed when calling, otherwise an error will be reported;
Mixing with parameter defaults:
// 定义
@mixin row($dir: column, $main: start){
display: flex;
flex-direction: $dir;
justify-content: $main
}
// 调用
.div1{
@include row();
}
.div2{
@include row(row);
}
.div3{
@include row(row, end);
}
.div4{
@include row(end);
}
.div5{
@include row(end, row);
}
// 解析
.div1{
display: flex;
flex-direction: column;
justify-content: start;
}
.div2{
display: flex;
flex-direction: row;
justify-content: start;
}
.div3{
display: flex;
flex-direction: row;
justify-content: end;
}
.div4{
display: flex;
flex-direction: end; // 错误语法
justify-content: start;
}
.div5{
display: flex;
flex-direction: end; // 错误语法
justify-content: row; // 错误语法
}
The order of passing parameters should be consistent with the order of definition, and cannot be omitted, but it can be called in the following way
When multiple parameters:
// 调用
.body{
@include row($main:start, $dir:row);
}
// 解析
.body{
display: flex;
flex-direction: row;
justify-content: start;
}
When there are many parameter elements (...):
// 定义
@mixin shadow($shadow...){
box-shadow: $shadow;
}
// 使用
.box{
@include shadow(0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04))
}
// 解析
.box{
box-shadow: 0 2px 4px rgb(0 0 0 / 12%), 0 0 6px rgb(0 0 0 / 4%);
}