sass的基本使用

228 阅读2分钟

sass变量

sass最重要的特性就是它为css引入了变量。可以把重复使用的css属性值定义成变量,然后通过变量名来引用他们无需重复写这一属性值。sass使用 符号来标识变量变量声明 符号来标识变量 变量声明 `color: pink; $font-size: 14px;`

变量引用 body { background-color: $color; height: 300px; }

嵌套css规则

sass可以让你只写一遍,且使样式可读性更高。

body {
    background-color: $color;
    height: 300px;
// css嵌套
    button {
        font-size: $font-size;
    }
    a {
        text-decoration: none;
    }
}
  • 父选择器的标识符 &

& 为使用一个特殊的sass选择器,即父元素选择器。在使用嵌套规则时,父选择器能对于嵌套规则如何解提供更好的控制,且可以放在任何一个选择器可出现的地方

button {
        font-size: $font-size;
    }
    a {
        text-decoration: none;
        //  &  父选择器标识符
        &:hover {
            color:lightseagreen;
        }
    }
}
  • 群组选择器的嵌套

群组选择器的规则会对命中群组中任何一个选择器的元素生效。

body{ h1, h2, h3 {margin-bottom: .8em} }

  • 子组合选择器和同层组合选择器:>、+和~;

同层全体组合选择器 ~ 同层相邻组合选择器 +

article {
    ~ article { border-top: 1px dashed #ccc }
    > section { background: #eee }
    dl {
      >dt { color: #333 }
      >dd { color: #555 }
    }
    nav + & { margin-top: 0 }
  }
  • 嵌套属性

把属性名从中划线-的地方断开,在根属性后边添加一个冒号:,紧跟一个{ }块,把子属性部分写在这个{ }块中。

h-ul{
    display: flex;
    justify-content: space-between;
    align-items: center;
    li{
        list-style: none;
    }
}

导入SASS文件

sass@import规则在生成css文件时就把相关文件导入进来。这意味着所有相关的样式被归纳到了同一个css文件中,而无需发起额外的下载请求。使用sass@import规则并不需要指明被导入文件的全名。

p1.png

  • 默认变量值

反复声明一个变量,只有最后一处声明有效且它会覆盖前边的值。

$info:blue;
$error:pink;
    button{
        color: $error;
    }
  • 嵌套导入

跟原生的css不同,sass允许@import命令写在css规则内。这种导入方式下,生成对应的css文件时,局部文件会被直接插入到css规则内导入它的地方

混合器

混合器使用@mixin标识符定义。用一个标识符给一大段样式赋予一个名字,这样你就可以轻易地通过引用这个名字重用这段样式

@mixin border-radius{
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
}

然后就可以在你的样式表中通过@include来使用这个混合器,放在你希望的任何地方。@include调用会把混合器中的所有样式提取出来放在@include被调用的地方。

button{
        color: $error;
        @include border-radius;
    }
  • 混合器的css规则

混合器中不仅可以包含属性,也可以包含css规则。

@mixin h-ul{
    display: flex;
    justify-content: space-between;
    align-items: center;
    li{
        list-style: none;
    }
}

当一个包含css规则的混合器通过@include包含在一个父规则中时,在混合器中的规则最终会生成父规则中的嵌套规则。

button{
        color: $error;
        @include border-radius;
        @include border(2px,solid,pink)  
    }
    a{
        @include border-radius;
    }
    ul{
        @include h-ul;
        //dotted 点线   dashed  虚线
        @include border($w:2px,$s:dotted,$c:pink)  
    }
  • 给混合器传参

混合器并不一定总得生成相同的样式。可以通过在@include混合器时给混合器传参,来定制混合器生成的精确样式。当@include混合器时,参数其实就是可以赋值给css属性值的变量。

// 给混合器传参数
@mixin border($w,$s,$c){
    border: $w $s $c;
}

当混合器被@include时,你可以把它当作一个css函数来传参。

ul{
        @include h-ul;
        //dotted 点线   dashed  虚线
        @include border($w:2px,$s:dotted,$c:pink)  
    }

使用选择器继承来精简css

通过@extend语法实现

    border: 1px solid red;
    background-color: pink;
}
span{
    @extend div;  //继承div
    font-size: 20px;
    background-color: transparent;   //可以覆盖继承的样式
}