占位符选择器

Sass 有一种特殊的选择器,称为“占位符”。它的外观和行为很像类选择器,但它以 % 开头,并且不包含在 CSS 输出中。事实上,任何包含占位符选择器的复杂选择器(逗号之间的选择器)都不包含在 CSS 中,任何选择器都包含占位符的样式规则也不包含在 CSS 中。

Playground

SCSS Syntax

.alert:hover, %strong-alert {
  font-weight: bold;
}

%strong-alert:hover {
  color: red;
}
Playground

Sass Syntax

.alert:hover, %strong-alert
  font-weight: bold


%strong-alert:hover
  color: red

CSS Output

.alert:hover {
  font-weight: bold;
}




不发出的选择器有什么用?还可以是 扩展!与类选择器不同,占位符如果不扩展的话就不会弄乱 CSS,并且它们不强制库的用户在其 HTML 中使用特定的类名。

¥What’s the use of a selector that isn’t emitted? It can still be extended! Unlike class selectors, placeholders don’t clutter up the CSS if they aren’t extended and they don’t mandate that users of a library use specific class names for their HTML.

Playground

SCSS Syntax

%toolbelt {
  box-sizing: border-box;
  border-top: 1px rgba(#000, .12) solid;
  padding: 16px 0;
  width: 100%;

  &:hover { border: 2px rgba(#000, .5) solid; }
}

.action-buttons {
  @extend %toolbelt;
  color: #4285f4;
}

.reset-buttons {
  @extend %toolbelt;
  color: #cddc39;
}
Playground

Sass Syntax

%toolbelt
  box-sizing: border-box
  border-top: 1px rgba(#000, .12) solid
  padding: 16px 0
  width: 100%

  &:hover
    border: 2px rgba(#000, .5) solid

.action-buttons
  @extend %toolbelt
  color: #4285f4


.reset-buttons
  @extend %toolbelt
  color: #cddc39

CSS Output

.reset-buttons, .action-buttons {
  box-sizing: border-box;
  border-top: 1px rgba(0, 0, 0, 0.12) solid;
  padding: 16px 0;
  width: 100%;
}
.reset-buttons:hover, .action-buttons:hover {
  border: 2px rgba(0, 0, 0, 0.5) solid;
}

.action-buttons {
  color: #4285f4;
}

.reset-buttons {
  color: #cddc39;
}

在编写可能使用也可能不使用每个样式规则的 Sass 库时,占位符选择器非常有用。根据经验,如果你只是为自己的应用编写样式表,那么最好扩展类选择器(如果有)。

¥Placeholder selectors are useful when writing a Sass library where each style rule may or may not be used. As a rule of thumb, if you’re writing a stylesheet just for your own app, it’s often better to just extend a class selector if one is available.