前言
在真实项目中我们需要写很多样式的文件,需要写公用样式,就会看到很多人写的sass中的循环,刚开始也挺懵的。
一、@each in使用
$font: (
font14:14px,
font16:16px,
font18:18px,
font20:20px,
);
$backgrounds:(
bgc14:rgb(0, 21, 255),
bgc16:rgb(69, 170, 91),
bgc18:rgb(255, 0, 230),
bgc12:rgb(189, 173, 31),
);
$widthall:(
width1:100px,
width2:200px,
width3:300px,
width4:400px,
);
$variables:(
font: $font,
backgrounds:$backgrounds,
widthall:$widthall,
);
@each $key,$val in $variables {
@each $keys,$vals in $val {
@if $key=='font'{
.text-#{$keys} {
font-size: $vals;
}
}
@if $key=='backgrounds'{
.text-#{$keys} {
background: $vals;
}
}
@if $key=='widthall'{
.text-#{$keys} {
width: $vals;
}
}
}
}
编译成css后的结果:
.text-font14 {
font-size: 14px;
}
.text-font16 {
font-size: 16px;
}
.text-font18 {
font-size: 18px;
}
.text-font20 {
font-size: 20px;
}
.text-bgc14 {
background: #0015ff;
}
.text-bgc16 {
background: #45aa5b;
}
.text-bgc18 {
background: #ff00e6;
}
.text-bgc12 {
background: #bdad1f;
}
.text-width1 {
width: 100px;
}
.text-width2 {
width: 200px;
}
.text-width3 {
width: 300px;
}
.text-width4 {
width: 400px;
}
二、@for from使用
$colors:red rgb(255, 0, 115) rgb(0, 85, 255) rgb(72, 255, 0) ;
@for $var from 1 through length($colors) {
.tex-#{$var} {
font-size:nth($colors,$var)
}
}
编译css后的结果:
.tex-1 {
font-size: red;
}
.tex-2 {
font-size: #ff0073;
}
.tex-3 {
font-size: #0055ff;
}
.tex-4 {
font-size: #48ff00;
}