sass-@mixin指令

90 阅读1分钟

定义与使用混合指令@mixin

/*
    js混合指令(Mixin)用于定义可重复使用的样式,混合指令可以包含所有的css规则,绝大部分sass规则,
    甚至通过参数功能引入变量,输出多样化的样式
*/
    @mixin mixin-name(){
        /*规则*/
    }

例-定义

//1.普通形式
@mixin block{
    width: 96%;
    margin-top: 20px;
    border-radius: 5px;
    border: 1px solid red;

    .text-style{
        color: yellow;
        font-size: 20px;
    }
}

//2.有参数形式
@mixin flex-align($altem){

    -webkit-box-align: $altem;
    -webkit-align-items: $altem;
    -ms-flex-align: $altem;
    align-items: $altem;

}
//3.多参数形式 (可设定初始值 不设定则必须传值)
@mixin block-margin($top:null,$bottom,$left,$right){

    margin-top: $top;
    margin-bottom: $bottom;
    margin-left: $left;
    margin-right: $right;
}


例-使用

p{
    @include block;
}

div{
    display: flex;
    // @include flex-align(center);
    @include flex-align($altem:center); //指定参数

    //@include block-margin(20px,10px ,2px ,3px );//多参数

    //全部传值
    //@include block-margin($top:10px,$bottom:10px ,$left:5px ,$right:5px);

    //部分传值
    @include block-margin($bottom:10px ,$left:5px ,$right:5px);

}

例-生成css

p {
  width: 96%;
  margin-top: 20px;
  border-radius: 5px;
  border: 1px solid red;
}
p .text-style {
  color: yellow;
  font-size: 20px;
}

div {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  margin-bottom: 10px;
  margin-left: 5px;
  margin-right: 5px;
}

@mixin 不定参数-使用

/*
    $direction:方向
    $gradients:颜色过渡的值列表
*/
@mixin linear-gradient($direction,$gradients...){

    background-color:nth($list: $gradients, $n: 1);
    background-image: linear-gradient($direction,$gradients);
}

.container{
    //默认第一个参数会给$direction 其他作为$gradients
    @include linear-gradient($direction:to right, yellow,red,white,green);
}

不定参数-生成css

/*
    $direction:方向
    $gradients:颜色过渡的值列表
*/
.container {
  background-color: yellow;
  background-image: -webkit-gradient(linear, left top, right top, from(yellow), color-stop(red), color-stop(white), to(green));
  background-image: linear-gradient(to right, yellow, red, white, green);
}