htmlcsscss-selectors

CSS Selector for Child of Parent's Sibling Element


If I've got this:

<div class="parent">
    <a href="#" id="trigger">Trigger</a>
</div>
<div class="sibling">
    <div id="change">Hello</div>
</div>

Is there a selector to grab #change when #trigger is hovered upon?

Like upon hover of #trigger, change the background of .sibling's #change element.

I'm looking for a pure CSS solution without javascript.


Solution

  • In a word: no.

    Given the current structure of your HTML (and the current state of CSS selectors), this is not possible. Perhaps we will get something like this in CSS4, but traversal like this is best left up to Javascript.

    You can obviously restructure your markup, and use the sibling selector:

    HTML

    <div class="parent">
        <a href="#" id="trigger">Trigger</a>
        <div class="sibling">
           <div id="change">Hello</div>
        </div>
    </div>
    

    CSS

    #trigger:hover + .sibling #change {
      color:red; 
    }
    

    codepen