Sass 完整指南

Sass 是一个 CSS 预处理器,完全兼容所有版本的 CSS。实际上,Sass 并没有真正为 CSS 语言添加任何新功能。只是在许多情况下可以可以帮助我们减少 CSS 重复的代码,节省开发时间。下面就来看看 Sass 中常用的功能吧!

1. 注释

在 Sass 中支持两种类型的注释:

// 注释一

/* 注释二 */

需要注意,当 Sass 编译成CSS时,第一种注释不会编译到CSS中(只在Sass文件中可见),第二种注释会编译到CSS中。

2. 嵌套

嵌套的写法是Sass的一大特点,通过嵌套这些代码,可以得到类似HTML结构的CSS代码,使代码更具可读性。

nav {
    background : #C39BD3;
    padding : 10px;
    height: 50px;
  
    ul {
        display: flex;
        list-style : none;
        justify-content: flex-end;

        li {
            color: white;
            margin-right: 10px;
        } 
    }
}

那为什么要使用嵌套呢?在CSS中,如果想为其父元素的继承元素定义样式,就必须每次都选择父元素:

html, body {
    height: 100%;
}

html #root, body #root {
    height: 100%;
}

html .div-with-button, body .div-with-button {
    background-color: black;
}

html .div-with-button button, body .div-with-button button {
    background-color: #e4c681;
}

html .div-with-button button:hover, body .div-with-button button:hover {
    background-color: #ffe082;
}

在Sass中就可以这样写,这样写就会使代码更加清晰、条理和简洁:

html, body {
  height: 100%;

  #root {
    height: 100%;
  }

  .div-with-button {
    background-color: black;

    button {
      background-color: #e4c681;

      &:hover {
        background-color: #ffe082;
      }
    }
  }
}

注意,在编写Sass时,要嵌套嵌套太深,尽量不要超过三层,超过之后就会导致代码难以维护,并且在编译为CSS时就会出现不必要的选择器,就会导致CSS文件变大。

我们还可以在嵌套中使用 &,比如鼠标在按钮上悬浮时,改变颜色。在CSS中是这样的:

button {
  background-color: #535353;
  color: #000;
}
button:hover {
  background-color: #000;
  color: #fff;
}

在Sass中就可以这么写:

button {
  background-color: #535353;
  color: #000;
  &:hover {
    background-color: #000;
    color: #fff;
  }
}

通常,& 总是指向它上面的元素,可以用于伪类和伪元素:

.box {
  &:focus{} 
  &:hover{}
  &:active{}
  &:first-child{} 
  &:nth-child(2){}
  &::after{
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李牌牌you

制作不易,有帮助的话关注一下哦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值