w3c / csswg-drafts

CSS Working Group Editor Drafts
https://drafts.csswg.org/
Other
4.52k stars 673 forks source link

[css-selectors] Proposal: `>>` combinator to ensure all elements between an ancestor and a descendant match a given selector #11309

Open benface opened 5 hours ago

benface commented 5 hours ago

I've needed something like this a few times, and I just thought of a way to express it.

Here's an example:

<div class="group">
  <div> <!-- any number of element layers here -->
    <div class="yellow-bg-on-nearest-group-hover">
      This element should have a yellow background when the root `.group` is hovered, because it's
      the nearest one to this element.
    </div>
  </div>
  <div class="group">
    <div> <!-- any number of element layers here -->
      <div class="yellow-bg-on-nearest-group-hover">
        This element should have a yellow background only when the nearest `.group` is hovered,
        but not when other elements in the root `.group` are.
      </div>
    </div>
  </div>
</div>

Here's how I'm picturing it:

.group:hover > .yellow-bg-on-nearest-group-hover,
.group:hover > :not(.group) >> .yellow-bg-on-nearest-group-hover {
  background-color: yellow;
}

It would be equivalent to the following, but with an infinite number of > :not(.group) >:

.group:hover > .yellow-bg-on-nearest-group-hover,
.group:hover > :not(.group) > .yellow-bg-on-nearest-group-hover, 
.group:hover > :not(.group) > :not(.group) > .yellow-bg-on-nearest-group-hover
.group:hover > :not(.group) > :not(.group) > :not(.group) > .yellow-bg-on-nearest-group-hover /* etc. */ {
  background-color: yellow;
}

It would basically repeat the selector that precedes >> an infinite number of times.

benface commented 4 hours ago

I just realized that a similar "continuous" combinator but for sibling elements (++), rather than ancestor/descendant, could make sense too, though I don't have a strong use case for it.