Sass
Sass,英文全稱“Syntactically Awesome StyleSheets”,是對 CSS 的擴(kuò)展。它添加了一些 CSS 語法不具有的新特性。Sass 讓開發(fā)者維護(hù)樣式表變得更簡單。
Sass 有兩種語法。第一種被稱為 SCSS(Sassy CSS),它是 CSS 語法的擴(kuò)充版本。也就是說,CSS 樣式表也是合法的 SCSS 文件。這種語法的樣式表文件以 .scss 為擴(kuò)展名。
第二種比較古老的語法,就是所說的縮排語法(或者直接就稱為“Sass”),它不使用花括號,而是通過縮排的方式來表達(dá)選擇符的嵌套層級,它也不使用分號,而是用換行符來分隔屬性。此種語法的樣式表文件需要以 .sass 作為擴(kuò)展名。
Sass:用 Sass 變量存儲數(shù)據(jù)
<style type='text/sass'>
$main-fonts: Arial, sans-serif;
$headings-color: green;
//To use variables:
h1 {
font-family: $main-fonts;
color: $headings-color;
}
</style>
Sass:用 Sass 嵌套 CSS
nav {
background-color: red;
ul {
list-style: none;
li {
display: inline-block;
}
}
}
Sass:用 Mixins 創(chuàng)建可重用 CSS
@mixin box-shadow($x, $y, $blur, $c){
-webkit-box-shadow: $x, $y, $blur, $c;
-moz-box-shadow: $x, $y, $blur, $c;
-ms-box-shadow: $x, $y, $blur, $c;
box-shadow: $x, $y, $blur, $c;
}
div {
@include box-shadow(0px, 0px, 4px, #fff);
}
Sass:使用 @if 和 @else 為你的樣式添加邏輯
<style type='text/sass'>
@mixin border-stroke($val) {
@if $val == light {
border: 1px solid black;
}
@else if $val == medium {
border: 3px solid black;
}
@else if $val == heavy {
border: 6px solid black;
}
@else {
border: none;
}
}
#box {
width: 150px;
height: 150px;
background-color: red;
@include border-stroke(medium);
}
</style>
Sass:使用 @for 創(chuàng)建一個 Sass 循環(huán)
@for $i from 1 through 12 {
.col-#{$i} { width: 100%/12 * $i; }
}
Sass:使用 @each 遍歷列表中的項(xiàng)目
$colors: (color1: blue, color2: red, color3: green);
@each $key, $color in $colors {
.#{$color}-text {color: $color;}
}
Sass:使用 @while 當(dāng)條件滿足時樣式生效
$x: 1;
@while $x< 13 {
.col-#{$x} { width: 100%/12 * $x;}
$x: $x + 1;
}
$x:1;
@while $x < 11 {
.text-#{$x} {
font-size: 2px + 10px*$x;
$x: $x + 1;
}
}
Sass:用 Partials 將你的樣式分成小塊
如果所有mixins都保存在名為 "_mixins.scss " 的partial中,并且在"main.scss "文件中需要它們,這是如何在主文件中使用它們:
// In the main.scss file
@import 'mixins'
Sass:將一組CSS樣式擴(kuò)展到另一個元素
Sass 有一個名為extend的功能,可以很容易地從一個元素中借用 CSS 規(guī)則并在另一個元素上重用它們。
.panel{
background-color: red;
height: 70px;
border: 2px solid green;
}
.big-panel{
@extend .panel;
width: 150px;
font-size: 2em;
}