整理一下关于scss的一些用法,用于日常的复习和使用 代码片段
1.关于变量
Scss可以自定义变量 支持字符串拼接的写法 js字符串拼接用${} Scss 用#{}拼接 &:父选择器 & 可拼接 &-height = content-height
$width:100px;
$size:16;
.main{
width:$width;
font-size:#{$size}px;
&::before{
content:'SCSS变量'
}
&-text{ // 等于 main-text
color:#fff;
}
}
2.mixin 混入 声明 @mixin 引入 @include $width... 表示可变参数
// $width... 不定参数
@mixin border($color){
border:1px solid $color;
}
.content{
@include border('#CCC')
}
3.继承 @extend 指令告诉 Scss 一个选择器的样式从另一选择器继承。 使用继承后 HTML标签中就不需要指定多个标签的类了 只用一个就行了 @extend 体现了代码的复用性
.a{
width:100px;
height:100px;
}
// b继承a的属性
.b{
@extend .a
}
4.function @function 函数名($width:200px){}
@funtion px2rem($px){ // rem的换算方法
return $px/100 * 1rem
}
.rem{
width:px2rem(100px)
}
5.if 指令 逻辑和js的语言用法一样
$num:100;
$num2:200;
@if $num >=50 {
width:100px;
color:red;
} @else if $num>100 {
width:100px;
color:blur;
} @else{
width:200px;
color:blur;
}
6.for 指令 循环给多个html赋值css属性 比如 a1,a2,a3,a4
.banber 里面有 banner1 banner2 banner3 通过for指令赋值
@for $i from 1 through 10 {
.banber${$i}{
width:100px;
height:100px;
background:#000;
}
}
7.@each 指令 同样也是循环 但与for不同的是 它遍历一个类似数组的列表 然后 循环每个item比for的扩展性强
html
<div class="each">
<p class='each1'> </p>
<p class='each2'> </p>
<p class='each3'> </p>
</div>
css
@each $item in each1,each2,each3{
.each .#{$item}{
width: 100px;
height: 100px;
text-align: center;
line-height: 100px;
margin-top: 20px;
margin-left: 20px;
background:red;
color: #fff;
&::before{
content: "each-#{$item}"
}
}
}