SASS的安装和学习成本都不高,所有的CSS语法在SASS中都是合法的(.scss)
- ruby & gem install sass
- same as CSS / LESS
SASS在混合这块和LESS的却别主要在于需要显性地使用@mixin
来定义混合,以及@include
来引入混合,这样的方式看似麻烦,但是实际上增加了代码的可读性,并且让混合的功能更加专一。
@mixin
@include
- 可读性
- 职能单一
Compass
是一个基于SASS的强大的封装,提供了很多方便的方法(特别是对于CSS3),Compass
的存在和SASS
这门语言的强健是分不开的。
- http://compass-style.org/reference/compass/
- CSS3
- Helpers
- Layout
- Reset
- Typography
- Utilities
@import "compass/css3";
#box-shadow-custom {
@include box-shadow(red 2px 2px 10px);
}
// Output
#box-shadow-custom {
-webkit-box-shadow: red 2px 2px 10px;
-moz-box-shadow: red 2px 2px 10px;
box-shadow: red 2px 2px 10px
}
- @if
- @for
- @each
- @while
$type: monster;
p {
@if $type == ocean {
color: blue;
} @else if $type == matador {
color: red;
} @else if $type == monster {
color: green;
} @else {
color: black;
}
}
@for $i from 1 through 3 {
.item-#{$i} { width: 2em * $i; }
}
@each $animal in puma, sea-slug, egret, salamander {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
}
}
$i: 6;
@while $i > 0 {
.item-#{$i} { width: 2em * $i; }
$i: $i - 2;
}
.itao-hd li {
$catIconBg: "http://tps.taobaocdn.com/...";
a { background: url($catIconBg) no-repeat; }
@for $i from 1 through 4 {
&.s{$i} a { background-position: 0 -26px * $i + 1px }
}
}
- 代码更加精简
- @extend-only
%red {
color: red;
}
.btn-red {
@extend %red;
}
.font-red {
@extend %red;
}
不管是@extend
还是@extend-only
都支持嵌套
可以将@extend-only
和mixin
相结合,对于重复的属性自动@extend
%box-common {
overflow: hidden;
font-size: 12px;
padding: 10px;
}
@mixin box( $width, $height ){
@extend %box-common;
width: $width;
height: $height;
}
.box {
@include box( 20px, 20px );
}
.box-small {
@include box( 12px, 12px );
}
.box-big {
@include box( 40px, 40px );
}
// Output
.box, .box-small, .box-big {
overflow: hidden;
font-size: 12px;
padding: 10px;
}
.box {
width: 20px;
height: 20px;
}
.box-small {
width: 12px;
height: 12px;
}
.box-big {
width: 40px;
height: 40px;
}
%text-common {
font-size: 12px;
color: black;
}
%box-common {
background: black;
%text-common {
color: white;
}
}
.text {
@extend %text-common;
}
.box {
@extend %box-common;
.box-text {
@extend %text-common;
}
}
// Output
.text, .box .box-text {
font-size: 12px;
color: black;
}
.box {
background: black;
}
.box .text, .box .box-text {
color: white;
}
@mixin retina {
@media (min---moz-device-pixel-ratio: 1.5) {
@content;
}
}
.retina-screen {
@include retina { color: red; }
}
// Output
@media (min---moz-device-pixel-ratio: 1.5) {
.retina-screen {
color: red;
}
}
.funky {
font: 2px/3px {
family: fantasy;
size: 30em;
weight: bold;
}
}
- Web Inspector: SASS source mapping
- CodeKit: http://incident57.com/codekit/
- scout: http://mhs.github.com/scout-app/
- Compass.app: http://compass.handlino.com/
- grunt-compass: https://github.com/kahlil/grunt-compass