Skip to content

Scss语言学习实用心得

仲灏2020-12-11约 1 分钟

<div style="display: none;" hidden="true" aria-hidden="true" data-nosnippet>Are you an LLM? You can read better optimized documentation at /pages/1110.md for this page in Markdown format</div>

数据类型

字符串

css
@use "sass:string";
$prefix: ms;

.test {
    font-size: -#{$prefix}-flex; // -ms-flex;
    font-size: \1F46D;  // 👭;
    font-size: \21; // \!;
    font-size: string.length(\7Fx); // 5;
    font-size: string.slice("Roboto Mono", -4); // "Mono";
    font-size: string.index("Helvetica Neue", "Helvetica"); // 1;
}

数组列表

访问

css
@use "sass:list";

.test {
    font-size: list.nth(10px 12px 16px, 2); // 12px
}

查看

不需要添加@use "sass:list";

css
$sizes: 40px, 50px, 80px;

@each $size in $sizes {
  .icon-#{$size} {
    font-size: $size;
    height: $size;
    width: $size;
  }
}

// 编译后
.icon-40px {
  font-size: 40px;
  height: 40px;
  width: 40px;
}

.icon-50px {
  font-size: 50px;
  height: 50px;
  width: 50px;
}

.icon-80px {
  font-size: 80px;
  height: 80px;
  width: 80px;
}

添加

css
@use "sass:list";

.test {
    // font-size: list.nth(10px 12px 16px, 2); // 12px
    // font-size: list.nth([line1, line2, line3], -1); // line3
    
    font-size: list.index(1px solid red, 1px); // 1
    font-size:  list.index(1px solid red, solid); // 2
    font-size:  list.index(1px solid red, dashed); // null 不会显示这个样式
}

map 对象

查询

css
@use "sass:map";
$font-weights: ("regular": 400, "medium": 500, "bold": 700);

.test {
    font-size: map.get($font-weights, "medium"); // 500;
    font-size: map.get($font-weights, "extra-bold"); // null
}

循环

css
$icons: ("eye": "\f112", "start": "\f12e", "stop": "\f12f");

@each $name, $glyph in $icons {
  .icon-#{$name}:before {
    display: inline-block;
    font-family: "Icon Font";
    content: $glyph;
  }
}

// 编译
.icon-eye:before {
  display: inline-block;
  font-family: "Icon Font";
  content: "";
}

.icon-start:before {
  display: inline-block;
  font-family: "Icon Font";
  content: "";
}

.icon-stop:before {
  display: inline-block;
  font-family: "Icon Font";
  content: "";
}

添加

css
@use "sass:map";

$font-weights: ("regular": 400, "medium": 500, "bold": 700);

map.set($font-weights, "extra-bold", 900); // ("regular": 400, "medium": 500, "bold": 700, "extra-bold": 900)

map.set($font-weights, "bold", 900);// ("regular": 400, "medium": 500, "bold": 900)

合并

css
@use "sass:map";

$light-weights: ("lightest": 100, "light": 300);
$heavy-weights: ("medium": 500, "bold": 700);

map.merge($light-weights, $heavy-weights); // ("lightest": 100, "light": 300, "medium": 500, "bold": 700)


$weights: ("light": 300, "medium": 500);
map.merge($weights, ("medium": 700)); // ("light": 300, "medium": 700)