如果你的样式里有很多都是重复的代码,那么你可以这样做,引入sass,然后定义一个mixin.scss文件,其中你可以定义一些方法,将宽高作为参数传入这个函数
//在style文件夹下定义一个mixin.scss文件
//定义宽高
@mixin wh($width, $height) {
width: $width;
height: $height;
}
//定义margin的值
@mixin mg($top, $right, $bottom, $left) {
margin-top: $top!important;
margin-left: $left;
margin-bottom: $bottom;
margin-right: $right;
}
混合器中使用css规则
@mixin no-button{
list-style: none;
li{
list-style-image: none;
list-style-type: none;
margin-left: 0px;
}
}
ul.plain{
color: #444;
@include no-button;
}
混合器传参、参数默认值及参数的顺序问题
混合器并不一定总得生成相同的样式。可以通过在@include
混合器时给混合器传参,来定制混合器生成的精确样式。当@include
混合器时,参数其实就是可以赋值给css
属性值的变量。如果你写过JavaScript
,这种方式跟JavaScript
的function
很像:
@mixin link-colors($normal, $hover, $visited) {
color: $normal;
&:hover { color: $hover; }
&:visited { color: $visited; }
}
当混合器被@include
时,你可以把它当作一个css
函数来传参。如果你像下边这样写:
a {
@include link-colors(blue, red, green);
}
//Sass最终生成的是:
a { color: blue; }
a:hover { color: red; }
a:visited { color: green; }
当你@include混合器时,有时候可能会很难区分每个参数是什么意思,参数之间是一个什么样的顺序。为了解决这个问题,sass
允许通过语法$name: value
的形式指定每个参数的值。这种形式的传参,参数顺序就不必再在乎了,只需要保证没有漏掉参数即可:
a {
@include link-colors(
$normal: blue,
$visited: green,
$hover: red
);
}
尽管给混合器加参数来实现定制很好,但是有时有些参数我们没有定制的需要,这时候也需要赋值一个变量就变成很痛苦的事情了。所以sass
允许混合器声明时给参数赋默认值。
选择器继承的使用
.error{
background-color: azure;
border: 1px solid rosybrown;
}
.seriousError{
@extend.error;
border-radius: 5px;
}