csscss-selectors

CSS - Is it possible to select multiple different child elements within a parent without repeating the parent?


I've been pawing over CSS selectors all afternoon in an attempt to find an answer to this because it seems so simple but I cannot for the life of me find any solution.

Given a structure similar to:

<div id="about">
    <h1></h1>
    <h2></h2>
    <h3></h3>
</div>

I want to make all of the headers a different typeface specific to this division using one selector.

My selectors would normally have been:

#about h1,
#about h2,
#about h3 {
}

Which now really appears to be inefficient. Is there a way to collate the ID?

#about h1 + h2 + h3 (incorrect)

Is there something akin to:

#about (h1,h2,h3)

I feel as if this should be obvious but I have never seen such a selection.


Solution

  • To complete Guffa answer, if you cannot use server side preprocessing and you have to target only Firefox and Chrome you can also use

    :-moz-any( selector[, selector]* )
    :-webkit-any( selector[, selector]* )
    

    in your case you will use this pseudoclass in this way

    #about :-moz-any(h1, h2, h3) { ... }
    

    otherwise the only crossbrowser method without using less or sass that reduce the amount of rules is the universal selector

    #about > *
    

    but this will target every immediate child of #about and it is intrinsically inefficient.


    Update 2023

    Now browsers support :is and :where pseudoclasses, so you may use them, e.g.:

    #about :is(h1, h2, h3) {
      ...
    }