Is there a single CSS selector for all descendants of X and also X itself?

Viewed 79

If I want to select an element with ID "Parent" and all of its descendants, I can do this:

#Parent, #Parent * { ... }

My question is: Is there a single selector that is equivalent to the above that doesn't require repeating #Parent twice?

In other words, is there a single selector that can select an element and all of its descendants at once?


Here is a snippet to play with, where #left, #left * and #right, #right * are the selectors of interest:

#layout { display: flex; }
#layout > div { flex: 1 }
#layout * { border: 1px solid black; margin: 4px; padding: 4px; }

/* #left _and_ its descendants */
#left, #left * { border-color: #f0f; }

/* #right _and_ its descendants */
#right, #right * { border-color: #0ff; }
<div id="layout">
  <div id="left">
    <div>test</div>
    <div><span>test</span><span>test</span></div>
    <div>test</div>
  </div>
  <div id="right">
    <div>test</div>
    <div><span>test</span><span>test</span></div>
    <div>test</div>
  </div>
</div>

2 Answers

If it's only about color or the same property/value then use CSS variables:

#layout { display: flex; }
#layout > div { flex: 1 }
#layout * { border: 1px solid var(--c,black); margin: 4px; padding: 4px; }

/* #left _and_ its descendants */
#left  { --c: #f0f; }

/* #right _and_ its descendants */
#right  { --c: #0ff; }
<div id="layout">
  <div id="left">
    <div>test</div>
    <div><span>test</span><span>test</span></div>
    <div>test</div>
  </div>
  <div id="right">
    <div>test</div>
    <div><span>test</span><span>test</span></div>
    <div>test</div>
  </div>
</div>

My question is: Is there a single selector that is equivalent to the above that doesn't require repeating #Parent twice?

No. There is not.

They are two different types of selectors, which is why they are defined separately in the spec.

One is a simple selector (#parent).

The other is a complex selector (#Parent *).

A combination of them both would require another type of selector, which doesn't exist in the current version of the spec.

Related