Sass官网入口 https://www.sass.hk/docs/
标题Sass 是一款强化 CSS 的辅助工具,它在 CSS 语法的基础上增加了变量 (variables)、嵌套 (nested rules)、混合 (mixins)、导入 (inline imports) 等高级功能,这些拓展令 CSS 更加强大与优雅。使用 Sass 以及 Sass 的样式库(如 Compass)有助于更好地组织管理样式文件,以及更高效地开发项目。
完全兼容 CSS3 在 CSS 基础上增加变量、嵌套 (nesting)、混合 (mixins) 等功能 通过函数进行颜色值与属性值的运算 提供控制指令 (control directives)等高级功能 自定义输出格式 Sass 自动缓存编译后的模板与 partials,这样做能够显著提升重新编译的速度,尤其在处理由 @import 导入多个子文件的大型项目时。 单独使用 Sass,缓存内容保存在 .sass-cache 文件夹中。在 Rails 和 Merb 项目中缓存文件保存在 tmp/sass-cache 文件夹中(可通过 :cache_location 修改路径)。禁用缓存可将 :cache 设为 false。
一、嵌套
// 层级嵌套, id 或 class 类名
#main{
width: 100%;
.container{
font-size: 16px;
}
button{
padding: 4px 6px;
&:after{
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
}
}
// 属性嵌套 font-family, font-size, font-weight; 三个属性的缩写
.container{
font:{
family: fantasy;
size: 30em;
weight: bold;
}
}
二、数据类型
/*
* 1. 数字类型
*/
1, 2, 15, 20px
/*
* 2. 字符串
*/
"fff", 'ccc', ddd
/*
* 3. 颜色值
*/
blue, #efefed, rgba(0,0,0,0.6)
/*
* 4. 布尔类型
*/
true, false
/*
* 5. 空值
*/
null
/*
* 6. 数组, 逗号隔开
*/
table-layout,table-layout-row, table-layout-col, table-layout-item
/*
* 7. 对象, map 类型 key:value
*/
(
key1: value1,
key2: value2,
key3: value3
)
三、运算符
sass 支持对数字的加减乘除运算
$w: 20px;
$h: 10px;
p{
font-size: $w / 2;
height: round($h) * 2;
padding: 5px + $h / 2;
}
四、插值语句(拼接字符)
#{ };
五、prefix
$prefix:"flex";
.#{$prefix}{
&-layout{
display:flex;
}
&-column{
flex-direction: column;
}
&-center{
justify-content: center;
align-items: center;
}
}
// 编译之后的结果
.flex{
.flex-layout{
display:flex;
}
.flex-column{
flex-direction: column;
}
.flex-center{
justify-content: center;
align-items: center;
}
}
六、循环控制
// each 循环
$array:(a,b,c,d);
@each $i in $array{
.#{$i}{
color:#ccc;
}
}
// for 循环, 不依赖数组
@for $i from 1 through 5 {
.item-#{$i} {
width: 2em * $i;
}
}
// while 循环
$i: 5;
@while $i > 0 {
.item-#{$i} {
width: 2em * $i;
}
$i:$i - 1;
}
七、函数
@function v($px){
@if $px == 0{
@return 0;
}
@return $px / 1334 * 100vw;
}
@function h($px){
@if $px == 0{
@return 0;
}
@return $px / 750 * 100vh;
}
.container{
width: v(520);
height: h(340);
}
八、混合指令
通常用于定义可重复的样式, 避免了无意义的 class 名;
@mixin clearfix {
display: inline-block;
&:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
* html & { height: 1px }
}
.list{
@include clearfix;
padding: 4px 0;
}
// 带参数的mixin
@mixin box-shadow($shadows...){
-moz-box-shadow: $shadows;
-webkit-box-shadow: $shadows;
box-shadow: $shadows;
}
.shadows{
@include box-shadow(0px 4px 5px #666, 2px 6px 10px #999);
}
九、extend 继承
.clearfix {
display: inline-block;
&:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
* html & { height: 1px }
}
.container{
padding: 5px 8px;
@extend .clearfix;
}