CSS 预处理器

219 阅读1分钟

这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战

Sass完全兼容所有版本的CSS。我们对此严格把控,所以你可以无缝地使用任何可用的CSS库。

  • 基于 CSS 的另一种语言
  • 通过工具编译成 CSS
  • 添加了很多 CSS 不具备的特性
  • 能提升 CSS 文件的组织

sass 声明变量

sass 使用 $ 符号声明变量。

$width: 300px;
$btn-primary-bg: #428bca;

.container {
    width: $width;
    background: $btn-primary-bg;
}
普通变量和默认变量

上面声明的变量是普通变量,默认变量一般用来设置默认值,只需要在值后面加上 !default

$width: 400px !default;

.container {
    width: $width;
}
局部变量和全局变量

定义在元素内部的变量是一个局部变量,定义在元素外面的变量是全局变量

$color: red;

.contaier {
    color: $color; // 调用全局变量
}

span {
    $color: blue;
    
    color: $color; // 调用局部变量
}

嵌套

sass 嵌套有三种:

  • 选择器嵌套
  • 属性嵌套
  • 伪类嵌套
选择器嵌套
/* css 写法 */
li a {
    color: #333;
    font-size: 18px;
}

.tab li a {
    color: blue;
    font-size: 16px;
}
/* sass 写法 */
li {
    a {
        color: #333;
        font-size: 18px;
    }
    
    .tab & {
        color: blue;
        font-size: 16px;
    }
}
属性嵌套

css 有一些属性前缀相同,后缀不一样,如:margin、padding、font,可以在 sass 中使用属性嵌套。

/* css */
.container {
    margin-top: 5px;
    margin-bottom: 10px;
}

/* sass */
.container {
    margin: {
        top: 5px;
        bottom: 10px;
    }
}
伪类嵌套

伪类嵌套和属性嵌套相似,需要用 & 配合使用:

.clearfix {
    &:before,
    &:after {
        content: "";
        display: table;
    }
    &:after {
        clear: both;
        overflow: hidden;
    }
}

混合宏

混合宏适合在需要重复使用大段的样式时候。

声明混合宏
  • 不带参数混合宏

使用 @mixin 声明一个混合宏

@mixin border-radius {
    -webkit-border-radius: 5px;
    border-radius: 5px;
}

border-radius 是混合宏的名称。

  • 带参数的混合宏
@mixin border-radius($radius: 5px) {
    -webkit-border-radius: $radius;
    border-radius: $radius;
}
  • 复杂的混合宏,带有逻辑关系
@mixin box-shadow($shadow...) {
    @if length($shadow) >= 1 {
        @include prefixer(box-shadow, $shadow);
    } @else {
        $shadow: 0 0 4px rgba(0,0,0,.3);
        @include prefixer(box-shadow, $shadow);
    }
}
调用混合宏

@mixin 声明混合宏,@include 调用混合宏。

@mixin border-radius {
    border-radius: 5px;
}

button {
    @include border-radius;
}