【翻译】对某些元素抵消样式不如活用选择器

115 阅读1分钟

我很认同Silvestar Bistrović的建议

An enabling selector is what I call a selector that does a job without disabling the particular rule.

一个经典的例子是将margin一股脑应用到所有元素后,却又不得不对最后一个元素删除margin,因为它在你不需要的地方又增加了空白。

.card {
  margin-bottom: 1rem;
}

/* Wait but not on the last one!! */
.parent-of-cards :last-child {
  margin-bottom: 0;
}

你可能这么做...

/* "Disabling" rule */
.card:last-child {
  margin-bottom: 0;
}

但是相比使用父级选择器,这么写可能并没有足够的上下文信息。

另一个写法是这样的:

.card:not(:last-child) {
  margin-bottom: 1rem;
}

这就是Silvestar所说的“enabling”,因为你只需要应用这项CSS rule,而不是应用某些CSS rule,然后使用另一个选择器删除它。我也觉得这理解起来有点困难,同时也容易出错。

另一个例子是Lobotomized Owls的精简版:

/* Only space them out if they stack */
.card + .card {
  margin-top: 1rem;
}

我认为长远来看gap才是方向。由父级承担职责,而不是子元素,因此可以使用如下选择器:

.parent-of-cards {
  display: grid;
  gap: 1rem;
}

原文:css-tricks.com/you-want-en…