简体   繁体   English

CSS / SCSS:两组选择器的笛卡尔积

[英]CSS/SCSS: cartesian product of two sets of selectors

I want to apply a CSS rule to all <ol> or <ul> that are next siblings of either a <h1> , <h2> , <h3> , or <h4> . 我想将CSS规则应用于<h1><h2><h3><h4>下一个同级的所有<ol><ul> <h4>

Something like this clearly doesn't work: 这样的事情显然是行不通的:

h1,h2,h3,h4 + ol,ul {
}

And parentheses to alter the order of evaluation seem to be not allowed in CSS. CSS中似乎不允许使用括号来更改评估顺序。

So, I have to write something like this: 所以,我必须写这样的东西:

h1 + ol, h1 + ul, h2 + ol, h2 + ul, h3 + ol, h3 + ul, h4 + ol, h4 + ul {
}

This works, but is quite long. 这有效,但是很长。 Is there any trick to achieve the same in a shorter and more scalable notation? 是否有任何技巧可以用更短,更可扩展的表示法实现相同目的? I'm using SCSS, so it can be either pure CSS or SCSS. 我正在使用SCSS,因此它可以是纯CSS或SCSS。

You can nest the selectors as such, using & to reference the parent selector in a nested context: 您可以这样嵌套选择器,使用&在嵌套上下文中引用父选择器:

h1, h2, h3, h4 {
    & + ol, & + ul {
        // Styles go here
    }
}

...this will generate the combination of all headings( h1 through h4 ) and its immediate sibling ( ul or ol ) in the selector format you wanted, <heading> + <list-parent> : ...这将以您想要的选择器格式<heading> + <list-parent>生成所有标题( h1h4 )及其直接同级( ulol )的组合:

h1 + ol, h1 + ul, h2 + ol, h2 + ul, h3 + ol, h3 + ul, h4 + ol, h4 + ul {
    // Styles go here
}

This still ends up being a tad bit verbose, because you have to manually comma-delineate each child combination, ie you can't use & + (ol, ul) { ... } for example. 最终还是有点冗长,因为您必须手动用逗号分隔每个子组合,例如,您不能使用& + (ol, ul) { ... } However, this is considerably better than other alternatives. 但是,这比其他选择要好得多。

Update: Using :matches() in CSS 4 working draft 更新:在CSS 4工作草案中使用:matches()

@IlyaStreltsyn noted in a comment below that :matches() [1] , [2] (previously known as :any , available via vendor prefixes, eg :-webkit-any() ) functional pseudo-class, part of the specification for CSS4, can be seen as a likely alternative solution that is way simpler: @IlyaStreltsyn在下面的评论中指出:matches() [1][2] (以前称为:any ,可通过供应商前缀使用,例如:-webkit-any() ),是该规范的一部分。 CSS4可以看作是一种可能更简单的替代解决方案:

:matches(h1, h2, h3, h4) + :matches(ol, ul) {
    // Styles go here
}

Note that the :matches() pseudo-class is still not widely supported across browsers at the time of writing (October 2017). 请注意,在撰写本文时(2017年10月), 仍未在所有浏览器广泛支持 :matches()伪类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM