sass揭秘之变量
1. 全局变量
p{
$color:blue;
color:$color;//blue
a{
$color:red;
color:$color;//red
}
background-color:$color;//red
span{
color:$color;//red
}
}
div{
color:$color;//$color未定义
}
2. !default
//第二种,使用前面定义的值
$color:red;
//变量申明带有!default,但是前面还有这个变量的申明
$color:blue !default;
p{
color:$color;//red
}
3. 变量用#{}包裹
$btnClass: btn !default;
$borderDirection: top !default;
.#{$btnClass}{
border-#{$borderDirection}:1px solid #ccc;
}
解析为:
.btn{
border-top:1px solid #ccc;
}
sass揭秘之@mixin,%,@function
4. API
length($var)
表示获取变量的长度nth($var,index)
获取变量第几个位置的值unitless
判断是否无单位if(unitless($width), $width + px, $width)
三目判断
5. @mixin和%
- @mixin可以传递参数,而%不行;
- @mixin的调用方式是@include,而%的调用方式是@extend;
- @include产生的样式是以复制拷贝的方式存在的,而@extend产生的样式是以组合申明的方式存在的。
1.@content
常用于定义media-queries,keyframes,浏览器兼容
@mixin header{
#header{
@content;
}
}
@include header{
width:1000px;
height:200px;
.logo{
width:200px;
}
}
解析为:
#header {
width: 1000px;
height: 200px;
}
#header .logo {
width: 200px;
}
2.@each
@each $prefix in $prefixes {
@if $prefix == webkit and $prefix-for-webkit == true {
-webkit-#{$property}: $value;
}
...
@else {
@warn "Unrecognized prefix: #{$prefix}";
}
}
3.@extend
继承,调用%
//sass style
//-------------------------------
h1{
border: 4px solid #ff9aa9;
}
.speaker{
@extend h1;
border-width: 2px;
}
//css style
//-------------------------------
h1,.speaker{
border: 4px solid #ff9aa9;
}
.speaker{
border-width: 2px;
}
4.%
组合申明
- 首先%定义的占位选择器样式不能传递参数。当然请注意不能传递参数,不代表样式里面不能使用变量。
- 然后@extend调用%申明的东西时,必须要把%带上,@extend %clearfix正确,而@extend clearfix是错误的调用。
- 最后%定义的样式,如果不调用是不会产生任何样式的,这也是用%定义样式比用原先的class方法定义样式高明的一方面。
%center-block {
@include center-block;
}
#header{
width:1000px;
@extend %center-block;
}
.gallery{
width:600px;
@extend %center-block;
}
解析为:
#header, .gallery {
margin-left: auto;
margin-right: auto;
}
#header {
width: 1000px;
}
.gallery {
width: 600px;
}