混合(mixin)
根据功能定义模块,然后在需要使用的地方通过 @include 调用,避免编码时重复输入代码段
// CSS
.jdc_1 {
-webkit-border-radius: 5px;
border-radius: 5px;
}
.jdc_2 {
-webkit-border-radius: 10px;
border-radius: 10px;
}
// SCSS
@mixin radius($radius:5px) {
-webkit-border-radius: $radius;
border-radius: $radius;
}
.jdc_1 {
@include radius; //参数使用默认值
}
.jdc_2 {
@include radius(10px);
}
// CSS
.jdc_1 {
background: url(/img/icon.png) no-repeat -10px 0;
}
.jdc_2 {
background: url(/img/icon.png) no-repeat -20px 0;
}
// SCSS
@mixin icon($x:0, $y:0) {
background: url(/img/icon.png) no-repeat $x, $y;
}
.jdc_1 {
@include icon(-10px, 0);
}
.jdc_2 {
@include icon(-20px, 0);
}
占位选择器 %
如果不调用则不会有任何多余的 css 文件,占位选择器以 % 标识定义,通过 @extend 调用
//scss
%borderbox {
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.jdc {
@extend %borderbox;
}
extend 继承
// CSS
.jdc_1 {
font-size: 12px;
color: red;
}
.jdc_2 {
font-size: 12px;
color: red;
font-weight: bold;
}
// SCSS
.jdc_1 {
font-size: 12px;
color: red;
}
.jdc_2 {
@extend .jdc_1;
font-weight: bold;
}
// 或者
%font_red {
font-size: 12px;
color: red;
}
.jdc_1 {
@extend %font_red;
}
.jdc_2 {
@extend %font_red;
font-weight: bold;
}
for 循环
注意:#{} 是连接符,变量连接使用时需要依赖
// CSS
.jdc_1 {background-position: 0 -20px;}
.jdc_2 {background-position: 0 -40px;}
.jdc_3 {background-position: 0 -60px;}
// SCSS
@for $i from 1 through 3 {
.jdc_#{$i} {
background-position: 0 (-20px) * $i;
}
}
each 循环
// CSS
.jdc_list {
background-image: url(/img/jdc_list.png);
}
.jdc_detail {
background-image: url(/img/jdc_detail.png);
}
// SCSS
@each $name in list, detail {
.jdc_#{$name} {
background-image: url(/img/jdc_#{$name}.png);
}
}
// CSS
.jdc_list {
background-image: url(/img/jdc_list.png);
background-color: red;
}
.jdc_detail {
background-image: url(/img/jdc_detail.png);
background-color: blue;
}
// SCSS
@each $name, $color in (list, red), (detail, blue) {
.jdc_#{$name} {
background-image: url(/img/jdc_#{$name}.png);
background-color: $color;
}
}
function 函数
@function pxToRem($px) {
@return $px / 10px * 1rem;
}
.jdc {
font-size: pxToRem(12px);
}