为了清晰起见,有没有办法对 CSS 选择器进行分组?

发布于 2024-10-13 11:47:42 字数 469 浏览 3 评论 0原文

如果我有十几个 CSS 选择器,并且想要为所有这些选择器分配 :hover 属性,我习惯这样做:

selector, selector2, someOtherSelector, someSelector div {
    //some properties
}
selector:hover, selector2:hover, someOtherSelector:hover, someSelector div:hover {
    //some properties
}

输入 :hover 四次似乎是多余的。有没有办法像这样对选择器进行分组

(selector, selector2, someOtherSelector, someSelector div):hover {
     //some properties
}

If I have a dozen CSS selectors, and want to assign :hover properties to all of them, I'm used to doing this:

selector, selector2, someOtherSelector, someSelector div {
    //some properties
}
selector:hover, selector2:hover, someOtherSelector:hover, someSelector div:hover {
    //some properties
}

Typing :hover four times seems redundant. Is there a way to group the selectors like

(selector, selector2, someOtherSelector, someSelector div):hover {
     //some properties
}

instead?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

捎一片雪花 2024-10-20 11:47:42

不是 CSS 原生的。通过使用诸如 SCSS 之类的东西,您可以编写:

selector, selector2, someOtherSelector, someSelector div {
  // some properties

  &:hover {
    // some more properties
  }
}

Not natively in CSS. By using something like SCSS, you can write:

selector, selector2, someOtherSelector, someSelector div {
  // some properties

  &:hover {
    // some more properties
  }
}
╭⌒浅淡时光〆 2024-10-20 11:47:42

如果它们都共享相同的悬停属性,您可以创建一个为所有定义您的 :hover 的人共享的类,

因此您会得到:

allSelectors, selector, selector2, someOtherSelector, someSelector div {
    //some properties
}
allSelectors:hover {
    //some properties
}

可重用的类使代码更干净、更少。

If they all share the same hover properties you could create a class that is shared for all that defines your :hover

So you'd get:

allSelectors, selector, selector2, someOtherSelector, someSelector div {
    //some properties
}
allSelectors:hover {
    //some properties
}

Re-usable classes makes for cleaner and less code.

烂柯人 2024-10-20 11:47:42

遗憾的是,实际上没有任何更简单的方法来做你想做的事情。除非你想将样式移至 jQuery 或其他东西(但这不是一个好的解决方案)。

Sadly, there's not really any easier way of doing what you're trying to do, unfortunately. Unless you want to move the styles to jQuery or something (but that's not a good solution).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文