使用 Sass Maps AWS Security LIVE 干燥 CSS 选择器!

2025-06-08

使用 Sass Maps 清除 CSS 选择器

AWS 安全上线!

第一次尝试:重复选择器

我最近写了一些与此类似的 Sass 代码:

$color-apple: green;
$color-lemon: yellow;
$color-strawberry: red;


.apple-button {
  background-color: $color-apple;
}

.strawberry-button {
  background-color: $color-strawberry;
}

.lemon-button {
  background-color: $color-lemon;
}

// This compiles to:

// .apple-button {
//   background-color: green;
// }
//
// .strawberry-button {
//   background-color: red;
// }
//
// .lemon-button {
//   background-color: yellow;
// }
Enter fullscreen mode Exit fullscreen mode

(不,我不是在为蔬菜水果商建立网站,水果主题只是为了举例说明!🍏🍓🍋)

乍一看,似乎还不错。

但是这段代码重复性很强。每个选择器的结构都相同,除了名称中的一个单词和颜色值不同。

此外,这种模式扩展性不高。如果我想添加 ablueberry-button和 a怎么办grape-button?我需要编写更多几乎相同的选择器。如果我想将颜色应用于字体而不是背景怎么办?我必须在多行中更改 CSS 属性。这效率太低了!

我们怎样才能重写这段代码,让它更短更简洁呢?也就是说,遵循DRY 原则不要重复自己)。就像这样:

重构:干选择器

$fruit-map: (
  apple: green,
  lemon: yellow,
  strawberry: red
);

@each $fruit, $fruit-colour in $fruit-map {
  .#{$fruit}-button--dry {
    background-color: #{$fruit-colour};
  }
}

// This compiles to:

// .apple-button--dry {
//   background-color: green;
// }
//
// .lemon-button--dry {
//   background-color: yellow;
// }
//
// .strawberry-button--dry {
//   background-color: red;
// }
Enter fullscreen mode Exit fullscreen mode

Sass的 map是键值对的集合,类似于 JavaScript 中的对象。在本例中,$fruit-map是一个 map。水果名称是键,颜色是值。

我们可以使用Sass 的 each 指令来迭代每一对。我们将键和值赋给变量,然后使用变量插值(即此语法#{$foobar})来构造选择器。

这段代码扩展性很好。如果我们想生成一个新的选择器,只需要在映射中添加一个新的键值对,例如blueberry: blue。如果我们想将颜色分配给字体而不是背景,只需要在一行中修改 CSS 属性,而无需修改多行代码。太棒了!

增强:多个值

等等,我们还可以更进一步!现在每个水果主题的按钮都有不同的边框样式了。我们如何调整 map,使每个键包含多个值呢?试试这个:

$fruitier-map: (
  apple: (green, 1px solid black),
  lemon: (yellow, 2px dashed grey),
  strawberry: (red, 3px dotted orange)
);

@each $fruit, $fruit-colours in $fruitier-map {
  $bg-colour: nth($fruit-colours, 1);
  $border-style: nth($fruit-colours, 2);

  .#{$fruit}-button--fruitier {
    background-color: #{$bg-colour};
    border: #{$border-style};
  }
}

// This compiles to:

// .apple-button--fruitier {
//   background-color: green;
//   border: 1px solid black;
// }
//
// .lemon-button--fruitier {
//   background-color: yellow;
//   border: 2px dashed grey;
// }
//
// .strawberry-button--fruitier {
//   background-color: red;
//   border: 3px dotted orange;
// }
Enter fullscreen mode Exit fullscreen mode
  • 将每个键的值转换为映射。将颜色和新的边框值添加到映射中。
  • 使用第 n 个函数访问每个地图元素并将它们分配给变量。
  • 像以前一样,使用这些变量来创建带有插值的动态 CSS 选择器。

最终的 Sass 代码易于扩展和维护,并且简洁明了。详尽的Sass 文档包含有关这些功能以及其他许多功能的更多详细信息。

鏂囩珷鏉ユ簮锛�https://dev.to/clairecodes/drying-out-css-selectors-with-sass-maps-1gem
PREV
如何防止粘贴到输入字段
NEXT
为什么我们不能用一行脚本标签来解决可访问性问题?