@mixin / @include
@mixin 定义要复用的样式;@include 引入复用的样式,两者结合使用,减少代码重复,提高代码复用率。
1、基本用法
## 定义
/* @minxin定义混入样式 */
@mixin clearfix {
&:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
}
## 使用案例
/* @include 引入定义的样式 可在某个样式下引入 */
.mybox {
@include clearfix;
...
}
/* 也可某个样式文件下直接引入 */
@include clearfix;
.mybox{
...
}
2、可传参数
## 定义
/***
params有三种(同函数)
无默认参数(a);有默认参数(a: 1); 不确定参数(params...)
***/
/* 字体 */
@mixin f-size($size: 14px) {
font-size: $size;
line-height: $size;
}
/* 对齐方式 */
@mixin t-align($align: center) {
text-align: $align;
}
/* 边框 */
@mixin border($col: #e6e6e6, $num: 1px, $solid: solid) {
border: $num $solid $col;
}
/* 按钮 */
@mixin btn($height: 36px, $font: 14px, $padding: 18px, $color: $white, $background: $mainColor, $num: 0, $border: $mainColor, $radius:4px) {
height: $height;
line-height: $height;
font-size: $font;
padding: 0 $padding;
color: $color;
background: $background;
border: $num solid $border;
display: inline-block;
border-radius: $radius;
box-sizing: border-box;
}
## 使用案例(携参)
/* btn */
.btn {
@include btn();
margin-right: 30px;
}
.btn1 {
@include btn(
$background: #fff,
$num: 1px,
$border: #dcdcdc,
$color: #333
);
}
ps:
1、sass中"-“与”_"等同,无区别
2、穿参数需带单位
@extend
@extend也可以复用样式
/* 清除浮动 */
.clear,
.clearfix {
*zoom: 1;
}
.clear:before,
.clear:after,
.clearfix:before,
.clearfix:after {
display: table;
line-height: 0;
content: "";
}
.clear:after,
.clearfix:after {
clear: both;
}
/* 单独使用 需要在当前使用业都写基本样式 */
.mybox{
@extend .clearfix;
}
/* 结合mixin使用 复用率更高*/
@mixin clearfix {
@extend .clearfix;
}