'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 1:[1]
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.
Solution 2:[2]
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 { ... }
}
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sayandcode |
Solution 2 | |
Solution 3 |