Positive look in css

I know that in Perl regex the concept of a positive kind, i.e. q(?=u) corresponds to q followed by u, without making the u-part of the match. I am looking for something like this in css: I want to match a div , followed by a sibling div.specialClass .

 <div>..</div> <!-- div to match --> <div class="specialClass">..</div> 

I played with +, but matched div.specialClass , whereas I need the previous div .

+9
css regex
source share
2 answers

You cannot yet declare which part of the selector is an object. The subject is always the last element of the selector in CSS until we get the opportunity to move it, probably using the $ or ! Syntax .

 // Always selects the .specialClass div which follows another div div + div.specialClass { color: red; } 

In the future, you can make the first div a subject, probably with the following syntax:

 // Selects any `div` preceding any `div.specialClass` $div + div.specialClass { // or maybe div! + div.specialClass color: red; } 

The only workaround for this is to use JavaScript. A tool like jQuery will make this very trivial:

 $("div + div.specialClass").prev(); 

Now this is a link to all div elements immediately preceding any div.specialClass .

Demo: http://jsfiddle.net/jonathansampson/HLfCr/
Source: http://dev.w3.org/csswg/selectors4/#subject

+10
source share

Not very useful now, but,

In the future, we could use the CSS4 :has() selector, in the future this will help.

The browser is currently not compatible at all .

 div:has(+div.specialClass) 
0
source share

All Articles