如何简化这些 CSS 选择器?

How can I simplify these CSS selectors?

我有一些代码我认为可能很庞大并且可以简化。我还没有找到任何对我的情况有帮助的东西。我试图做到这一点,以便当我将鼠标悬停在 div 上时,h2p 会带有下划线。它像这样工作得很好:

.test:hover h2, .test:hover p {
  text-decoration: underline;
}

但我想知道我是否可以通过某种方式简化它,而不必重复 .test:hover 两次。

有一个新的 pseudo-class :is 将允许这个..

The :is() CSS pseudo-class function takes a selector list as its argument, and selects any element that can be selected by one of the selectors in that list.

.test:hover :is(h2, p) {
  color: red;
  text-decoration: underline;
}
<div class="test">
  <h2>Heading</h2>
</div>

<div class="test">
  <p>Lorem ipsum dolor sit amet.</p>
</div>

如果您不需要支持 Internet Explorer,可以使用 :is pseudo-class:

.test:hover :is(h2, p) {
  text-decoration: underline;
}
<div class="test">
  <h1>An H1</h1>
  <h2>An H2</h2>
  <p>A paragraph</p>
</div>

另一种方法是利用 CSS 预处理器,如 Sass 或 Less,它们都支持嵌套,可以使 DRY-er 更具表现力的源代码风格。不过,这在您的情况下可能有点矫枉过正。这是 Sass' SCSS 格式的示例:

.test:hover {
  h2, p {
    text-decoration: underline;
  }
}

你可以使用它:

:is(h1, p) .test:hover { 
  text-decoration: underline; 
}