Sass 是一款强化 CSS 的辅助工具,它在 CSS 语法的基础上增加了变量 (variables)、嵌套 (nested rules)、混合 (mixins)、导入 (inline imports) 等高级功能,这些拓展令 CSS 更加强大与优雅。
/*html*/
<div id="test">
<div class="content">1</div>
<div class="content">2</div>
<div class="content">3</div>
</div>
<div id="demo"></div>
- 声明变量
$
$color:red; //全局变量
#test{
$width:10px;
color:$color
}
- 嵌套结构,用
&表示父级选择器
$color:#010203;
#test{
color:$color;
& .content{
width:50vw;
}
&:hover{
color:darken($color,10%) //sass:color文档有具体color使用介绍;
}
}
- 支持运算
+-*/%
$width=100px;
#test{
width:$width/2+('10px'-'5px'); //和数学运算规则一样;
}
- 数据类型 (Data Types)
SassScript 支持 6 种主要的数据类型:
- 数字,1, 2, 13, 10px
- 字符串,有引号字符串与无引号字符串,"foo", 'bar', baz
- 颜色,blue, #04a3f9, rgba(255,0,0,0.5)
- 布尔型,true, false
- 空值,null
- 数组 (list),用空格或逗号作分隔符,1.5em 1em 0 2em, Helvetica, Arial, sans-serif maps, 相当于 JavaScript 的 object,(key1: value1, key2: value2)
- 插值
#{}
$name:'.content'
#test #{$name}{ //插值时,将带引号字符串转为无引号字符串
color:rgba(24,26,254,.5)
}
if函数
$color:red; //全局变量
#test{
@if $color==red {
color:red
}@else {
color:grey
}
}
for函数
@for $i from 0 through 2{
.content:nth-child(#{$i}){
font-size:16px*($i+1)
}
}
each函数
@each $animal in puma, sea-slug, egret, salamander {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
}
}
- 导入
*.scss文件
/*foo.scss*/
@import "foo.scss";
@extend继承样式
#test{
width:100px;
}
#demo{
@extend #test
}
- 占位符
%placeholder
%foo-bar{ //设置一个占位符,方便@extend调用
font-size:16px;
color:red;
}
#test{
@extend %foo-bar
}
@mixin和@include
@mixin large-text { //注册共有样式
font: {
family: Arial;
size: 20px;
weight: bold;
}
color: #ff0000;
}
@mixin diy($size){
font-size:$size
}
#test {
@include large-text; //混入名为large-text的样式
@include diy(16px);
padding: 4px;
margin-top: 10px;
}
- 函数指令
$grid-width: 40px;
$gutter-width: 10px;
@function grid-width($n) {
@return $n * $grid-width + ($n - 1) * $gutter-width;
}
#sidebar { width: grid-width(5); }
最后
简单说一下less和styl的用法
** less: **
- 声明变量用
@ - 混入某个样式,直接
.className()or#idName() - 子级嵌套直接写在内部,不用
&,除非像&:hover同级嵌套时,需要& - 计算值
calc() - 转译符号
~"anything",可将任何字符串转译为变量或者属性 - Less还提供了各种功能,可以转换颜色,操纵字符串和进行数学运算
- Namespaces and Accessors、Maps、Scope等功能,看个例子就懂
- 导入文件也是
@import 路径
** styl: **
- 声明变量多样性
self-size=16px
#test{
height:100px;
width:@height;
border-top:b=10px;
border-bottom:b
}
- 嵌套可省掉
{}
ul
margin: 0
li
list-style: none
a
display: block
text-decoration: none
padding: 5px 10px
&:hover
text-decoration: underline
- 可以向书写javascript那样书写
var styl = require('styl');
var css = styl('body\n color: blue', { whitespace: true }).toString();
总之,styl还有很多强大功能,styl功能更强大,但使用也更晦涩。