Skip to content

变量

  1. 用于定义属性值(不能是属性名)
  2. 美元符$开头,具有块级作用域
  3. 可以引用其他变量 $light-border: 1px solid \$ligth-color
  4. 变量中命令不区分 下划线和中横线,一般统一风格就行

属性嵌套

scss
div {
  border: {
    // 冒号隔开
    width: 1px solid;
    left: 0;
    right: 0;
  }
}

div {
  border:  width: 1px solid {
    // 冒号隔开
    left: 0;
    right: 0;
  }
}

@import

导入文件中定义的变量和混合器, 如果在这个文件中重新定义变量会影响后面所有的变量值

如果 a.scss 定义了$a, b 引入 a.scss 并重写了, 后面再次引用 a.scss 的文件均是 b 重写过的

解决方案

  1. 使用默认值定义 $width: 400px !default(这样不会覆盖)
  2. 使用嵌套引入,将引入的作为局部变量 div {@import ""}

@mixin

将片段 复用,理解成讲这个片段完整拷贝到@include 位置

@mixin name {xxxxx} 定义 @include name; 使用

  1. 可以使用 &

  2. 可以包含块

  3. 可以带参数 @mixin name($arg1, $arg2), @include name(red,blue)

  4. 具名参数 @mixin name($arg1, $arg2), @include name({$arg2: blue, $arg1: red)

  5. 默认参数 @mixin name($arg1: red, $arg2: \$agr1) 可以对形参进行引用

@extends

继承其他选择器的属性, 仅是那个选择器, 不会包括选择器子元素那些

继承在 BEM 中实战

scss
.nav {
  background-color: steelblue;
  &__container {
    display: flex;
    justify-content: space-between;
  }
  &__item {
    color: white;
    &--active {
      @extend .nav__item;
      border-bottom: 1px solid red;
    }
  }
}
// 可以在html中直接 .nav__item--active 而不需要使用  .nav__item .nav__item--active

变量的数据类型

修正之前变量的错误认识

  1. 数字,1, 2, 13, 10px
  2. 字符串,有引号字符串与无引号字符串,"foo", 'bar', baz
  3. 颜色,blue, #04a3f9, rgba(255,0,0,0.5)
  4. 布尔型,true, false
  5. 空值,null
  6. 数组 (list),用空格或逗号作分隔符,1.5em 1em 0 2em, Helvetica, Arial, sans-serif,同时包含(空格 ,)时分解为子数组
  7. maps, 相当于 JavaScript 的 object,(key1: value1, key2: value2)

#{}插值语句

可以避免运算,直接编译

&的理解

理解成一个特殊的变量

scss
@mixin does-parent-exist {
  @if & {
    &:hover {
      color: red;
    }
  } @else {
    a {
      color: red;
    }
  }
}
scss
$light-theme: (
  border-color: #eceeef,
  font-color: #323232,
  font-secondary: #c2c6d0,
  background-color: #fff,
  bg-title: #d3e6fb,
  bg-oddList: #f3f3f3,
  bg-listHover: #c5dffe
);

//深色主题
$dark-theme: (
  border-color: #000,
  font-color: #c2c6d0,
  font-secondary: #aaa,
  background-color: #131925,
  bg-title: #293248,
  bg-oddList: #171e2c,
  bg-listHover: #0d3a70
);

//定义映射集合
$themes: (
  light: $light-theme,
  dark: $dark-theme
);

@mixin themify($themes: $themes) {
  @each $theme-name, $map in $themes {
    .theme-#{$theme-name} & {
      $theme-map: () !global;
      @each $key, $value in $map {
        $theme-map: map-merge(
          $theme-map,
          (
            $key: $value
          )
        ) !global;
      }

      @content;

      $theme-map: null !global;
    }
  }
}

@function themed($key) {
  @return map-get($theme-map, $key);
}

#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  @include themify($themes) {
    background: themed("background-color");
    color: themed("font-color");
  }
}

@each

scss
@each $item, $index in $list {
}