michaellee
michaellee

Reputation: 1352

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.

Upvotes: 23

Views: 22672

Answers (3)

red5
red5

Reputation: 312

For browsers that support the :has() pseudo-class, this works for me:

.parent:has(#trigger:hover) ~ .sibling #change {
  background-color: red;
}
<div class="parent">
  <a href="#" id="trigger">Hover me</a>
</div>
<div class="sibling">
  <div id="change">Hello</div>
</div>

Upvotes: 2

Nick Tomlin
Nick Tomlin

Reputation: 29221

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

Upvotes: 28

Yotam Omer
Yotam Omer

Reputation: 15356

No. You cannot achieve this using CSS only. Javascript is a good option in this case..

You can however detect the .parent being hovered (which will solve your problem if the parent surrounds exactly the trigger):

.parent:hover + .sibling div#change{background:red;}

(markup stays the same jsFiddle)

Upvotes: 3

Related Questions