Stephan
Stephan

Reputation: 43033

How to write this 'OR' CSS selector?

Here is an HTML fragment:

<div class="wrapper">
    <div class="ebook">
         <div class="page"></div>
    </div>

    <div class="book">
         <div class="page"></div>
    </div>

    <div class="document">
         <div class="page"></div>
    </div>
</div>

I want to match all divs with the page class with parents divs having ebook or book classes only. This selector can be used:

div.ebook div.page, div.book div.page

However is there a CSS engine suporting the following syntax ?

(div.ebook, div.book) div.page

or better

div.?book div.page

I'm not interested with a solution like this: div:not(.document) > div.page.

Upvotes: 1

Views: 1540

Answers (3)

BoltClock
BoltClock

Reputation: 723749

The proposed syntax takes the form of a functional pseudo-class called :matches():

/* As this is a pseudo-class, you can make it a little DRYer by saying
   div:matches(.ebook, .book) div.page instead */
:matches(div.ebook, div.book) div.page

If you really want to get technical, Firefox implements it as :-moz-any():

:-moz-any(div.ebook, div.book) div.page

and Chrome implements it as :-webkit-any():

:-webkit-any(div.ebook, div.book) div.page

(and these actually came first prior to the selector being specced as :matches())

But if you're using them in CSS you will have to duplicate your rulesets because of certain CSS parsing rules, which is as good as not using them at all (in fact, worse). These selectors are meant for internal use only, not for production.

What you currently have is the only viable option for now.

If you want to cheat a little, you could use a substring attribute selector, but that assumes each of those elements will have exactly one class only, and no other class names will match by this particular substring (this is similar to the div.?book example you have, but it comes with the limitations of an attribute selector that are not present in a class selector):

div[class$="book"] div.page

Personally, I'd just stick with the verbose option because it's more robust.

Upvotes: 5

Delorian
Delorian

Reputation: 340

Check out this Fiddle that should do what you're looking for:

http://jsfiddle.net/Delorian/L44u0p8r/

div[class$="book"] { 
    background-color: yellow;
}

Further details: https://stackoverflow.com/a/9836182/3264286

Upvotes: 1

Bill
Bill

Reputation: 3517

There is no such thing as an OR selector in CSS, except for as in the example you gave, where a comma (,) can be used to separate multiple selectors e.g;

div.ebook div.page,
div.book div.page{
    // CSS properties
}

Upvotes: 0

Related Questions