Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 437
Jake Avatar asked Jan 25 '12 08:01

Jake


3 Answers

The :is() selector should do what you mention. For your specific example

<div id="about">
    <h1>My</h1>
    <h2>Name</h2>
    <h3>Is</h3>

, you could use the is() selector as

#about :is(h1,h2,h3) {
  color:red;  //or whatever property you want to add
}

Check out this video for more info.

like image 73
sayandcode Avatar answered Oct 19 '22 01:10

sayandcode


In plain CSS it's not possible. If you set a class on the header tags you can target them with a single selector.

Using something like less, you can do:

#about {
  h1, h2, h3 { ... }
}
like image 41
Guffa Avatar answered Oct 19 '22 02:10

Guffa


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.

like image 34
Fabrizio Calderan Avatar answered Oct 19 '22 02:10

Fabrizio Calderan