Sass(css预处理)
什么是sass?
Sass是一个将脚本解析成CSS的脚本语言,即SassScript。Sass包括两套语法。最开始的语法叫做“缩进语法”,与Haml类似[3],使用缩进来区分代码块,并且用回车将不同规则分隔开。而较新的语法叫做“SCSS”,使用和CSS一样的块语法,即使用大括号将不同的规则分开,使用分号将具体的样式分开。通常情况下,这两套语法通过.sass和.scss两个文件扩展名区分开。
sas的出现使得css变得灵活,打开sass的git仓库你会看见:
$font-stack: Helvetica, sans-serif;
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
-ms-border-radius: $radius;
border-radius: $radius;
}
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { @include border-radius(10px); }
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
以上基本上展示了sass一些让人激动的写法与特性。
1、$ 符号
指明一个变量,用以代替某一些经常出现的属性。
如上面代码中的$ primary-color,他会代替 #333;
2、@ mixin
混合指令,这个特性用来定义可重复使用的样式,
如上面所示: border-radius
3、@include
@include 指令引用混合样式
如上所示:li { @include border-radius(10px); }
注意:
@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
-ms-border-radius: $radius;
border-radius: $radius;
}
这里面引用了一个变量,实现了四行代码解决跨浏览器设置圆角的问题!
控制指令
@if
$type: monster;
p {
@if $type == ocean {
color: blue;
} @else if $type == matador {
color: red;
} @else if $type == monster {
color: green;
} @else {
color: black;
}
}
结果为:
p {
color: green; }
@for
@for $i from 1 through 3 {
.item-#{$i} { width: 2em * $i; }
}
结果为:
.item-1 { width: 2em; }
.item-2 { width: 4em; }
.item-3 { width: 6em; }
@each
@each $animal, $color, $cursor in (puma, black, default),
(sea-slug, blue, pointer),
(egret, white, move) {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
border: 2px solid $color;
cursor: $cursor;
}
}
结果为:
.puma-icon {
background-image: url('/images/puma.png');
border: 2px solid black;
cursor: default; }
.sea-slug-icon {
background-image: url('/images/sea-slug.png');
border: 2px solid blue;
cursor: pointer; }
.egret-icon {
background-image: url('/images/egret.png');
border: 2px solid white;
cursor: move; }
@while
$i: 6;
@while $i > 0 {
.item-#{$i} { width: 2em * $i; }
$i: $i - 2;
}
结果为:
.item-6 {
width: 12em; }
.item-4 {
width: 8em; }
.item-2 {
width: 4em; }
sass的出现,让css编程成为可能。