SASS如何使用@mixin和@include?代码示例

2021年3月25日13:05:38 发表评论 630 次浏览

Mixins可用于对可以分配不同值的样式进行分组, 并且可以像函数一样多次使用。我们还可以像函数一样在mixin中传递参数, 这使我们可以编写可重用的代码。

Mixins是使用@mixin at-rule定义的, 并且可以在当前上下文中使用@include at-rule来使用。

Mixins可以通过两种方式使用:没有参数和有参数。

不带参数:

当我们不需要更改属性的值时, 即我们想要一次又一次使用具有相同属性值的一组属性时, 可以使用这种类型的mixin。

语法如下:

  • 定义mixin:@mixin name_of_mixin {…}
  • 要在当前块中使用mixin:@include name_of_mixin; 。
@mixin block-name{
    property-1: value;
    property-2: value;
        ...
    property-n: value;
}

block-name2{
    @include block-name;
}

SCSS文件:

@mixin first-mixin {
    width: 100%;
    overflow: hidden;
    color: gray;
}
            
@mixin second-mixin {
    @include first-mixin;
            
    ul {
        list-style-type: none;
    }
            
    li {
        display: inline-block;
        width: 100px;
        padding: 5px 10px;
    }
            
    li a {
        text-decoration: none;
    }
            
}
            
navigationbar {
    @include second-mixin;
}

编译的CSS文件:

navigationbar {
    width: 100%;
    overflow: hidden;
    color: gray;
}

navigationbar ul {
    list-style-type: none;
}

navigationbar li {
    display: inline-block;
    width: 100px;
    padding: 5px 10px;
}

navigationbar li a {
    text-decoration: none;
}

带有参数:

当我们想一次又一次地使用一组具有不同值的属性, 并且可以使用诸如function之类的参数传递不同的值时, 可以使用这种类型的mixin。这里, 参数默认值的概念与任何其他编程语言相同。

语法如下:

  • 定义mixin:@mixin name_of_mixin(参数…){…}
  • 要在当前块中使用mixin:@include name_of_mixin(arguments…);
// Here default values are optional

@mixin block-name($parameter1, $parameter2: default, ...) {
                
    property-1: $parameter1;
    property-2: $parameter2;
    // You can use all the parameters 
    // same as variables
}

block-name2 {
    @include block-name($argument1, $argument2, ...);
}

SASS文件:

// Here blue is default value of $three

@mixin first-mixin($one, $two, $three: blue) {
    width: $one;
    overflow: $two;
    color: $three;
}

@mixin second-mixin($one, $two, $three, $four) {
    // Don't need to pass the third argument if 
        // the default value is same as your argument.
    @include first-mixin($one, $two /*, Default*/);

    ul {
        list-style-type: none;
    }

    li {
        display: inline-block;
        width: $four;
        padding: 5px 10px;
    }

    li a {
        text-decoration: none;
    }

}

navigationbar {
    @include second-mixin(100%, hidden, blue, 100px);
}

编译的CSS文件:

navigationbar {
  width: 100%;
  overflow: hidden;
  color: blue;
}

navigationbar ul {
  list-style-type: none;
}

navigationbar li {
  display: inline-block;
  width: 100px;
  padding: 5px 10px;
}

navigationbar li a {
  text-decoration: none;
}

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: