Sass(Syntactically Awesome Stylesheets)是一种CSS预处理器,它扩展了CSS的功能,使得CSS的编写更加高效和易于维护。Sass主要通过提供变量、嵌套、混合、继承等特性来增强CSS的功能。
安装Sass
你可以通过以下几种方式安装Sass:
使用npm安装:
npm install -g sass
使用Yarn安装:
yarn global add sass
Sass语法
Sass有两种语法:.scss
和 .sass
。.scss
是Sass的扩展语法,更接近CSS的语法;.sass 是缩进语法,更简洁但与CSS差别较大。以下主要介绍.scss语法,因为它更广泛使用。
基本特性
- 变量
变量能够存储CSS属性值,以便在整个样式表中重复使用。
$primary-color: #333;body {color: $primary-color;
}
- 嵌套
Sass允许在选择器中嵌套其他选择器,类似于HTML的结构。
nav {ul {margin: 0;padding: 0;list-style: none;}li { display: inline-block; }a {text-decoration: none;&:hover {text-decoration: underline;}}
}
- 混合(Mixins)
混合允许你定义可重用的CSS代码块,随后在其他地方调用。
@mixin border-radius($radius) {-webkit-border-radius: $radius;-moz-border-radius: $radius;-ms-border-radius: $radius;border-radius: $radius;
}
.box { @include border-radius(10px); }
- 继承(Inheritance)
继承允许一个选择器继承另一个选择器的样式。
.message {border: 1px solid #ccc;padding: 10px;color: #333;
}.success {@extend .message;border-color: green;
}.error {@extend .message;border-color: red;
}
- 运算
Sass支持在CSS属性中进行数学运算。
.container {width: 100%;
}.main {width: 600px / 960px * 100%;
}
- 插值(Interpolation)
插值允许在选择器或属性名称中使用变量。
$side: left;
.rounded {border-#{$side}-radius: 5px;
}
- 函数
Sass允许你定义自己的函数,以便在样式表中使用。
@function double($n) {@return $n * 2;
}.container {width: double(5px);
}
- 条件和循环
Sass支持基本的条件语句和循环。
@mixin theme-colors($theme) {@if $theme == light {background: white;color: black;} @else if $theme == dark {background: black;color: white;} @else {background: gray;color: black;}
}body {@include theme-colors(dark);
}@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');}
}
编译Sass
你可以使用以下命令将Sass文件编译为CSS文件:
sass input.scss output.css
或者实时编译:
sass --watch input.scss:output.css
总结
Sass通过提供变量、嵌套、混合、继承、运算、插值、函数、条件和循环等功能,使得CSS的编写更加高效和灵活。通过学习和使用Sass,你可以大大提高样式表的可维护性和重用性。