在css中使用模块,过多的css文件再加会产生很多http请求,影响用户体验。但是在sass中可以解决该问题。
功能模块的命名
_layout.scss
_variables.scss
引入功能的scss的命名
index.scss
other.scss
引入模块: 把每个功能模块独立成一个文件,引入到功能的scss,再使用sass工具打包成css文件
@import "模块名字"
@import "_layout.scss";
注释: 在scss中可以使用两种注释,一种可编译到css文件中,一种删除不编译到css文件中
/**/ 可以编译
// 删除不编译
变量: 使用$+name: 值
全局变量:可以在全局使用
/* !default 遇到相同变量时不使用 没有遇到才使用 */
$error-color: #ccc !default;
局部变量:只能在局部使用
.alert-error {
$text_color: #ddd;
background-color: $error-color;
color: $text_color;
text-shadow: 0 0 2px darken($text_color, 40%)
}
Mixins语法: 使用@mixin+name 定义代码块,使用@include+name引入代码块
代码复用
@mixin alert-text {
background-color: #f00;
color: white;
font-variant: small-caps;
}
.error-text {
@include alert-text;
}
.has-error:after {
@include alert-text;
display: inline-block;
content: attr(data-error);
}
Mixins传参: 可以传参数
@mixin alert-text($color) {
background-color: $color;
color: white;
font-variant: small-caps;
}
.error-text {
@include alert-text(blue);
}
.has-error:after {
@include alert-text(red);
display: inline-block;
content: attr(data-error);
}
Mixins默认传参
@mixin alert-text($color: pink) {
background-color: $color;
color: white;
font-variant: small-caps;
}
.error-text {
@include alert-text;
}
.has-error:after {
@include alert-text(red);
display: inline-block;
content: attr(data-error);
}
多个传参
@mixin alert-text($color1: pink, $color2: pink) {
background-color: $color1;
color: $color2;
font-variant: small-caps;
}
.error-text {
@include alert-text(blue);
}
.has-error:after {
@include alert-text($color2: black);
display: inline-block;
content: attr(data-error);
}
在参数中传null值表示删除该属性
@mixin alert-text($color1: pink, $color2: pink) {
background-color: $color1;
color: $color2;
font-variant: small-caps;
}
.error-text {
@include alert-text(null);
}
.has-error:after {
@include alert-text($color2: null);
display: inline-block;
content: attr(data-error);
}
传一个块: 块中的为私有选择器
@mixin foo($color) {
color: $color;
.inner {
@content
}
}
.btn {
@include foo(#c69) {
color: red;
// 块中的为私有选择器
}
}
.btn {
@include foo(#ccd)
}
结果为
.btn {
color: #c69;
}
.btn .inner {
/* 块中的东西 */
color: red;
}
.btn {
color: #ccd;
}