Sass 是一个 CSS 预处理器,完全兼容所有版本的 CSS。实际上,Sass 并没有真正为 CSS 语言添加任何新功能。只是在许多情况下可以可以帮助我们减少 CSS 重复的代码,节省开发时间。下面就来看看 Sass 中常用的功能吧!
1. 注释
在 Sass 中支持两种类型的注释:
// 注释一
/* 注释二 */
需要注意,当 Sass 编译成CSS时,第一种注释不会编译到CSS中(只在Sass文件中可见),第二种注释会编译到CSS中。
2. 嵌套
嵌套的写法是Sass的一大特点,通过嵌套这些代码,可以得到类似HTML结构的CSS代码,使代码更具可读性。
nav {
background : #C39BD3;
padding : 10px;
height: 50px;
ul {
display: flex;
list-style : none;
justify-content: flex-end;
li {
color: white;
margin-right: 10px;
}
}
}
那为什么要使用嵌套呢?在CSS中,如果想为其父元素的继承元素定义样式,就必须每次都选择父元素:
html, body {
height: 100%;
}
html #root, body #root {
height: 100%;
}
html .div-with-button, body .div-with-button {
background-color: black;
}
html .div-with-button button, body .div-with-button button {
background-color: #e4c681;
}
html .div-with-button button:hover, body .div-with-button button:hover {
background-color: #ffe082;
}
在Sass中就可以这样写,这样写就会使代码更加清晰、条理和简洁:
html, body {
height: 100%;
#root {
height: 100%;
}
.div-with-button {
background-color: black;
button {
background-color: #e4c681;
&:hover {
background-color: #ffe082;
}
}
}
}
注意,在编写Sass时,要嵌套嵌套太深,尽量不要超过三层,超过之后就会导致代码难以维护,并且在编译为CSS时就会出现不必要的选择器,就会导致CSS文件变大。
我们还可以在嵌套中使用 &
,比如鼠标在按钮上悬浮时,改变颜色。在CSS中是这样的:
button {
background-color: #535353;
color: #000;
}
button:hover {
background-color: #000;
color: #fff;
}
在Sass中就可以这么写:
button {
background-color: #535353;
color: #000;
&:hover {
background-color: #000;
color: #fff;
}
}
通常,& 总是指向它上面的元素,可以用于伪类和伪元素:
.box {
&:focus{}
&:hover{}
&:active{}
&:first-child{}
&:nth-child(2){}
&::after{