scss混合mixin与继承extend的使用(混合篇)

混合(Mixin)

理解:

包含多个样式的‘变量’,定义的混合若不使用,就不会解析到css样式中;使用过后,解析时,相当于将定义的样式复制到使用的位置。

优点:

可以传参。

缺点:

因为解析时是复制代码,解析后会有大量代码。

基本使用:

定义混合:
@mixin mixin-name() {
    /* css 声明 */
}


使用混合:
body{
    @include mixin-name();
    ...
}

解析格式:
body{
    /* css 声明 */
}

带参数的混合:

// 定义
@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;
}


但是定义了参数,调用时就必须传参,不然会报错;

带参数默认值的混合:

// 定义
@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;  // 错误语法
}

传参顺序要与定义顺序一致,不可漏传,但可用下方方式调用

多个参数时:

// 调用
.body{
    @include row($main:start, $dir:row);
}


// 解析
.body{
    display: flex;
    flex-direction: row;
    justify-content: start;
}

参数元素较多时(...):

// 定义
@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%);
}

猜你喜欢

转载自blog.csdn.net/weixin_59128282/article/details/119242159