文章目录
1.变量
常见使用场景
把css文件中经常使用的颜色设置为一个变量,
当用户需要不同的主题时,只需要改变此变量的值即可,
而不是修改每一个css文件中涉及到背景色,字体颜色的代码行
语法
$variablename: value;
定义:$变量名:变量值
使用:元素属性名:$变量名
示例
index.scss
$color1:blue;
$color2:white;
$num:150px;
div {
height: $num*2;
width: $num*2;
background-color: $color1;
p {
height: $num;
width: $num;
margin: 0 auto;
background-color: $color2;
border-radius: 50%;
}
}
生成的index.css
div {
height: 300px;
width: 300px;
background-color: blue;
}
div p {
height: 150px;
width: 150px;
margin: 0 auto;
background-color: white;
border-radius: 50%;
}
2.条件分支
常见使用场景
语法
@if(判断语句){
css代码1
}
@else{
css代码2
}
示例
game.scss
$hand:"left";
@if($hand=="right") {
#box {
width: 100px;
height: 100px;
background-color: black;
}
}
@else {
#box {
width: 100px;
height: 100px;
background-color: red;
}
}
game.css
#box {
width: 100px;
height: 100px;
background-color: red;
}
3.循环
常见使用场景
子节点的元素样式的属性值呈规律性递增时使用循环
语法
1.@for 指令
@for 指令可以用于循环生成样式,有两种类型,如下所示:
第一种:使用关键字 to 不会包括 end 这个数
@for $变量名 from <起始值> to <结束值>
第二种:使用关键字 through 时会包括 end 这个数
@for $变量名 from <起始值> through <结束值>
2.@each 指令
@each 指令可以用于遍历一个列表,然后从列表中取出对应的值
@each $变量名 in <数组>
示例一:for循环li节点的样式
box.scss
//css的循环是从1开始的,js的循环是从0开始的
@for $item from 1 to 6 {
li:nth-child(#{$item}) { // 注意此处选择器的格式:"#"号表示{}里面是js语法
width: 100px;
height: 100px;
background: pink;
position: absolute;
top: ($item - 1)*100px;
left: ($item - 1)*100px;
// top: $item*100px;
// left: $item*100px;
}
}
生成box.css
li:nth-child(1) {
...
top: 0px;
left: 0px;
}
...
li:nth-child(5) {
...
top: 400px;
left: 400px;
}
示例二:each…in节点的样式
scss文件:
$col:red blue green;//颜色列表
@each $item in $col {
$index: index($col, $item);//此处调用了系统的索引函数index(list,item)
li:nth-child(#{$index}) {
background: $item;
}
}
css文件:
li:nth-child(1) {
background: red;
}
li:nth-child(2) {
background: blue;
}
li:nth-child(3) {
background: green;
}
4.混合(Mixin)
@mixin 指令允许我们定义一个可以在整个样式表中重复使用的样式。
@include 指令可以将混入(mixin)引入到文档中。
语法
定义一个混入
@mixin mixin-name{
css样式
}
使用混入
selector {
@include mixin-name;
}
示例
scss:
@mixin liStyle {//设置
width: 150px;
height: 150px;
}
li:nth-child(1) {
@include liStyle();//引入
background: red;
}
li:nth-child(2) {
@include liStyle();
background: blue;
}
li:nth-child(3) {
@include liStyle();
background: green;
}
css:
li:nth-child(1) {
width: 150px;
height: 150px;
background: red;
}
li:nth-child(2) {
width: 150px;
height: 150px;
background: blue;
}
li:nth-child(3) {
width: 150px;
height: 150px;
background: green;
}
5.知识点
5.1.索引函数$idx:index($list,$item)
5.2.css的循环是从1开始的
5.3.浏览器兼容性
-moz- 是火狐浏览器厂商前缀
-webkit- 是谷歌浏览器厂商前缀
-o- 是opera浏览器厂商前缀