sass的基础用法

时间:2022-07-22
本文章向大家介绍sass的基础用法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前端发展到现在都有了不小的改变,今天主要谈一下css扩展语法sass的基本用法和语法。

sass是什么?

Sass 是一款强化 CSS 的辅助工具,它在 CSS 语法的基础上增加了变量 、嵌套 、混合 、导入  等高级功能,这些拓展令 CSS 的开发更加便捷。

我们此篇不讲安装和编译,我们只说语法。

1.变量声明

sass使用$符号来声明变量:

$color:red

调用:

color:$color

2.嵌套语法

我们知道html是有层级的,但是css却不支持层级,sass完美解决了这个问题。

.main{
    font-size: 24px;
    a,span{
        font-size:14px ;
    }
}

输出:

.main {
  font-size: 24px;
}

.main a, .main span {
  font-size: 14px;
}

3.父元素&

在Sass中,&表示父元素。

.wx{
    transition: all 1s;
    &:hover{
        transform: scale(1.5);
    }
}

输出为:

.wx {
  transition: all 1s;
}

.wx:hover {
  transform: scale(1.5);
}

4.控制语句@if

$common:".index";
#{$common} section{
    background-color: #ccc;
    width: 100%;
    height: 100px+50px;
    @if 3==3{
        height:350px ;
    }
}

输出为:

.index section {
  background-color: #ccc;
  width: 100%;
  height: 150px;
  height: 350px;
}

5.循环语句from...through..

@for $i from 1 through 3{
    .test-#{$i}{height: 10px*$i; background-color: gray;}
}

输出为:

.test-1 {
  height: 10px;
  background-color: gray;
}

.test-2 {
  height: 20px;
  background-color: gray;
}

.test-3 {
  height: 30px;
  background-color: gray;
}

6.循环语句@each

@each $var in blue,red,green {
    .#{$var}{
        color: $var;
    }
}

 输出为:

.blue {
  color: blue;
}

.red {
  color: red;
}

.green {
  color: green;
}

7.代码重用Mixin

@mixin clearleft($size,$color2) {
    &{
        font-size: $size;
        color:$color2;
        clear:both;
    }
}
.mixin{@include clearleft(22px,red);}

输出为:

.mixin {
  font-size: 22px;
  color: red;
  clear: both;
}

以上就是sass重用的7个知识点,其实还有其他知识点,只是不常用,所以我就不一 一列举了。

如无作者授权,请勿转载。