1、@mixin @include 混合
@mixin mixin-dot-status(**backColor**){ // backColor为变量,可以方便重定义背景色
height:8px;
width:8px;
border-radius:50%;
margin-right:5px;
background: $backColor
}
.all-dot-status-1{
@include mixin-dot-status(#13CE66);
}
.all-dot-status-2{
@include mixin-dot-status(#F12F46);
}
编译出来的css,不影响使用,但没有把相同的样式合并在一起。
.all-dot-status-1{
height:8px;
width:8px;
border-radius:50%;
margin-right:5px;
background: #13CE66
}
.all-dot-status-2{
height:8px;
width:8px;
border-radius:50%;
margin-right:5px;
background: #F12F46
}
2、占位符 %placeholder 和 @extend
%dot-status{
height:8px;
width:8px;
border-radius:50%;
margin-right:5px;
}
.all-dot-status-1{
@extend %dot-status;
background: #13CE66
}
.all-dot-status-2{
@extend %dot-status;
background: #F12F46
}
编译出来的css,不影响使用,并且把相同的样式合并在一起。
.all-dot-status-1, .all-dot-status-2 {
height: 8px;
width: 8px;
border-radius: 50%;
margin-right: 5px;
}
.all-dot-status-1 {
background: #13CE66;
}
.all-dot-status-2 {
background: #F12F46;
}
当然@extend也可以直接使用 类选择器,
形如:
.btn { padding: 5px 15px; }
.btn-plan {
@extend .btn;
background-color: #409EFF;
}
编译后:
.btn, .btn-plan{
padding: 5px 15px;
}
.btn-plan {
background-color: #409EFF;
}
这样都可以直接使用,更为方便,如
<div class="btn">我是普通按钮</div><div class="btn-plan">我是有背景色的按钮</div>
3、总结:@include VS @extend
两者在代码编写和页面渲染样式中几乎一模一样,唯独就是编译后的Css代码不一样,那么在使用中就要考虑,编译出来的CSS样式,接近重用的样式对当前项目是不是很重要。在某些情况下, @extend 可以大大的减化CSS输出,并且显著的提高CSS性能。(当前场景看来,实现all-dot-status 这个样式还是需要@extend更为优化)
附加题:
@extend有个弊端:他不能在不同的 @media 中运行,因为 @extend 是将一个选择器样式扩展到另一个选择器当中,而实际上在不同的 @media 中却无需复制这些样式。
错误写法:
%dot-status{
height:8px;
width:8px;
border-radius:50%;
margin-right:5px;
}
@media screen {
.all-dot-status-1{
@extend %dot-status;
background: #13CE66
}
.all-dot-status-2{
@extend %dot-status;
background: #F12F46
}
}
编译报错:
Syntax Error:
%dot-status{
^
You may not @extend an outer selector from within @media.
You may only @extend selectors within the same directive.
From "@extend %dot-status" on line 313 of src/styles/mystyle.scss
修改后:
@media screen and (max-width:500px){
%dot-status{
height:8px;
width:8px;
border-radius:50%;
margin-right:5px;
}
}
.all-dot-status-1{
@extend %dot-status;
background: #13CE66
}
.all-dot-status-2{
@extend %dot-status;
background: #F12F46
}
编译后:
@media screen and (max-width:500px){
.all-dot-status-1, .all-dot-status-2 {
height: 8px;
width: 8px;
border-radius: 50%;
margin-right: 5px;
}
}
.all-dot-status-2 {
background: #F12F46;
}