csscss-selectors

Selector for subsequent sibling of element containing specific item


Is there a css way to select elements of X type which are after element Y type containing Z type elements?

Given the following html, i could only after the Z type, not after the Y type containing Z.

.y .z:after {
  color: green;
  /* x is not green because it's after y, not z */
}
<span class="y">
  y
  <span class "z">
    z
  </span>
</span>
<span class="x">
  x
</span>


Solution

  • No

    Because there is no method of selecting UP the DOM...yet.

    There is, under CSS3, no parent selector or previous sibling selector.

    CSS4 offers the :has selector in which case you would be able to use

    .y:has( > .z) + .x
    

    and it is being supported by all major browsers since the end of 2023 at least (see).


    Note: The ::after 'element' is, in fact, a pseudo-element, not a selector, used primarily, for styling purposes for inserting "content" inside the element to which the ::after pseudo-element is attached.