How to select multiple elements that are children of given element?

CssCss Selectors

Css Problem Overview


I have <div id='mydiv'> and I need to select all pre and div elements that are children of #mydiv.

I could do it this way:

div#mydiv > pre, div#mydiv > div

but, can it be done so that #mydiv is referenced only once?

div#mydiv > pre, div

will select all divs on the page regardless if they're children of #mydiv, so the comma isn't a way to do it. Maybe there's another kind of syntax I don't know about?

Css Solutions


Solution 1 - Css

You'll have to reference #mydiv twice...

#mydiv > pre, #mydiv > div

I removed the extraneous div element selector as the ID is specific enough.

Solution 2 - Css

As far as I know, there is no shorthand for selector grouping.

See "Selector Grouping".

Although, with LESS, it is possible in the "Nested Rules" section.

Solution 3 - Css

The only way to reference the id only once is to use it with the * selector:

#mydiv > * {

which will apply to all elements that are children of that div.

Depending on what styles you plan to apply this might be workable (I typically use this to zero-out margins, padding and border styles), but it's still probably best to do it the first way because it makes it easier to make exceptions/changes later down the road.

Solution 4 - Css

You can actually group selectors with :is().

So in your case you would use it like this:

div#mydiv > :is(pre, div) {
     // CSS
}

Here is the documentation https://developer.mozilla.org/en-US/docs/Web/CSS/:is

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrsk82View Question on Stackoverflow
Solution 1 - CssFoscoView Answer on Stackoverflow
Solution 2 - CssJawadView Answer on Stackoverflow
Solution 3 - CssEast of NowhereView Answer on Stackoverflow
Solution 4 - CssIssam MejdoubiView Answer on Stackoverflow