Grouping Css Selectors (i.e. child OR selectors)

2019-05-14 03:44发布

问题:

Is it possible to nest or group selectors together? For example I have the following css:

.feature > *:hover > .info,
.feature > .select > .info   {bottom:0;}
.feature > *:hover > .img,
.feature > .select > .img,
.feature > *:hover > .link,
.feature > .select > .link   {top:-25px;bottom:51px;}

Is it possible to group many of the selectors in a way similar to the following pseudo CSS (I'm using brackets, but I realise this doesn't work) :

.feature > (*:hover,.select) > .info         {bottom:0;}
.feature > (*:hover,.select) > (.img,.link)  {top:-25px;bottom:51px;}

I notice that CSS3 has the :not() selector, but I couldn't find an :or() selector.

回答1:

:any() is implemented in Fx 4+ as :-moz-any() (and Saf 5.1 and Chr 12+ as :-webkit-any(), though I never tested on WebKit), see https://developer.mozilla.org/en-US/docs/CSS/:any

Note : This pseudo-class is in progress to be standardized in CSS Selectors Level 4 under the name :matches(). It is likely that the syntax and name of :-vendor-any() will be changed to reflect it in the near future.

This is quite OK in a media query @-rule (except for recent IE) and otherwise you should add an HTML class to the element you want to style and use this class in your CSS selector. Or use a preprocessor where nesting will save you a few repeats.

See @Christoph answer for the near future and :matches()



回答2:

It will be possible with the :matches() pseudo class which is defined in Selectors Level 4 (which is currently at status Editor's Draft and thus subject to change), which is currently implemented in none of the browsers :-D

Until then you are doomed to write it exactly like you did.



回答3:

No, it is unfortunately not possible under normal circumstances. You would have to use a CSS preprocessor like:

  1. LESS
  2. SASS

An example:

.feature {
    > *:hover, > .select {
        .info {
            bottom: 0;
        }
    } 
 }


回答4:

No, grouping of many css selectors into one line is not possible with CSS. They have to be broken out each with their own line.