Is it possible to efficiently select the inverse of a certain element using only one selector?
One way to achieve this is by using the :any()
pseudo-class
Currently, only a few browsers support the :any() pseudo-class, which will eventually be replaced by :matches
The syntax for using this feature is as follows:
:-moz-any( <selector># ) { style properties }
:-webkit-any( <selector># ) { style properties }
Therefore, the original selector can be refactored as:
div:-webkit-any(.two, .three, .four):not(.one)
Check out a demo showcasing the use of :any()
with the provided syntax.
div:-webkit-any(.two, .three, .four):not(.one) {
width: 100px;
background-color: red;
}
div{
width:100px;
border: 1px solid black;
}
<div class="one">1</div>
<div class="two one">2</div>
<div class="three">3</div>
<div class="four one">4</div>
https://i.sstatic.net/epFo2.png
Potential Future Options.
Another upcoming option is the :matches() selector
The :matches pseudo-class is described as a functional pseudo-class by the official CSS Selectors Level 4 specifications. It doesn't serve any purpose in itself except making some complex selectors lighter by allowing them to be grouped. In a way, we can think as :matches as syntactic sugar.
This will allow for the following functionality:
div:matches(.two,.three,.four) :not(.one) { /*your styles*/}
Alternative Approaches
An alternative approach is to assign a common class, for example number
, to all relevant elements
Subsequently, you can use the following selector:
div.number:not(.one)