LOADING

sass

2023/12/26

嵌套

Sass 允许将一套 CSS 样式嵌套进另一套样式中,内层的样式将它外层的选择器作为父选择器。嵌套功能避免了重复输入父选择器,而且令复杂的 CSS 结构更易于管理。

1、选择器嵌套

#app{
  color:while;
  // 嵌套
  .content{
  color:red;
    }
}
编译结果:
#app {
  color: while;
}
#app .content {
  color: red;
}

2、父级选择器 &
在嵌套 CSS 规则时,有时也需要直接使用嵌套外层的父选择器,可以用 & 代表嵌套规则外层的父选择器。

#app{
  color:while;
  // 父级选择器
  &.chird{
    background:#f0f0f0;
  }
}
编译结果:
#app {
    color: while;
}
#app.chird {
    background: #f0f0f0;
}

3、属性嵌套
有些 CSS 属性遵循相同的命名空间 (namespace),比如 font-family, font-size, font-weight 都以 font 作为属性的命名空间。为了便于管理这样的属性,同时也为了避免了重复输入,Sass 允许将属性嵌套在命名空间中

#app{
    color:while;
    // 嵌套
    .content{
        color:red;
    }
    // 父级选择器
    &.chird{
        background:#f0f0f0;
        // 属性嵌套
        font:{
            family:test;
            size:30px;
            weight:bold;
        }
    }
}

编译结果:
#app {
  color: while;
}
#app .content {
  color: red;
}
#app.chird {
  background: #f0f0f0;
  font-family: test;
  font-size: 30px;
  font-weight: bold;
}

变量

使用变量,可运算

$var : 16px;
.fontSize {
    font-size: $var;
  width: $var * 2 ;
}

编译结果:
.fontSize {
    font-size: 16px;
}

混入

编写函数

// 定义页面一个区块基本的样式
@mixin block {
    width: 96%;
    margin-left: 2%;
    border-radius: 8px;
    border: 1px #f6f6f6 solid;
}

.button {
  @include block;
  padding: 10px 20px;
}