什么是Sass
SASS是一种CSS的开发工具,提供了许多便利的写法,大大节省了设计者的时间,使得CSS的开发,变得简单和可维护。
Sass的基本用法
变量
变量的简单使用
$blue: #1875e7;
div {
/* 这样写就相当于 color: #1875e7; */
color : $blue;
}
变量的嵌套
$side: left;
div {
/* 这样写就相当于 border-left-color: #1875e7; */
border-#{$side}-color : #1875e7;
}
计算
body {
margin: (14px/2);
top: 50px + 100px;
right: $var * 10%;
}
嵌套
div {
/* 这里的 & 相当于 引用父元素,代编的是div */
& + h1 {
/* 属性的嵌套 相当于 margin-left: 10px */
margin: {
left: 10px;
}
}
}
注释
// 单行注释只会保留在SASS源文件中
/* 标准注释,会保留到编译后的文件中 */
/*!
重要注释:压缩模式也会保留
*/
继承
继承作用:代码的重用。
.text-red {
color: red;
}
.tips-content {
/* tips-content类中继承了text-red中的样式 */
@extend .text-red;
}
@mixin left {
float: left;
}
div {
/* @include left 就相当于 float:left */
@include left;
}
@mixin right($value: 10px) {
margin-left: $value;
}
div + p {
/* 使用的时候根据需要传参,默认是10px */
@include right(20px);
}
插入文件
@import 'theme.css';
高级用法
/*颜色的内置函数:*/
/*lighten(#cc3, 10%) ———— #d6d65c*/
/*darken(#cc3, 10%) ———— #a3a329*/
/*grayscale(#cc3) ———— #808080*/
/*complement(#cc3) ———— #33c*/
@if lightness($color) > 30% {
background-color: #000;
} @else {
background-color: #fff;
}
/*for循环*/
@for $i from 1 to 10 {
.border-#{$i} {
border: #{$i}px solid blue;
}
}
/* to的结束是9,相当于[1, 9] */
/*使用: class="border-9" 相当于 border: 9px solid blue; */
@for $i from 1 through 10 {
.border-#{$i} {
border: #{$i}px solid blue;
}
}
/* through的结束是10,相当于[1, 10] */
/*使用: class="border-9" 相当于 border: 9px solid blue; */
$i: 6;
@while $i > 0 {
.item-#{$i} {
width: 2em * $i;
}
}
/* 注意: 这里的1 2 3 4 5 可以写为 1..5, 相当于 [1, 5]; 如果要使用1 2 3 4 5只取到4, 就可以写成 1..5 相当于 【1, 4) */
table
for row in 1 2 3 4 5
tr:nth-child({row})
height: 10px * row
就相当于
table tr:nth-child(1) {
height: 10px;
}
table tr:nth-child(2) {
height: 20px;
}
table tr:nth-child(3) {
height: 30px;
}
table tr:nth-child(4) {
height: 40px;
}
table tr:nth-child(5) {
height: 50px;
}
@each $member in a, b, c, d {
.#{$member} {
background-image: url("/image/#{$member}.jpg");
}
}
自定义函数
@function double($n) {
@return $n * 2;
}
#sidebar {
width: double(5px);
}
详情请见stylus官网