Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 923
michaellee Avatar asked Jul 22 '13 17:07

michaellee


People also ask

How do I select a parent sibling in CSS?

Adjacent Sibling Selector (+) The adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".

How do I apply CSS to child element based on parent?

It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinator ( > ), which is placed between two CSS selectors. For example, div > p selects all <p> elements where the parent is a <div> element.

Can CSS be used to find child => parent page element?

Yes, it's possible. We can check with CSS @supports rule like the following.

How do you target siblings in CSS?

CSS All Next Siblings Selector - CSS ~ Sign Selector CSS all next siblings selector matches all element they are siblings of specified element. This Selector identify by ~ (tilde sign) between two selector element. All next siblings selected match all elements whose are sibling of specified element.


2 Answers

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

like image 70
Nick Tomlin Avatar answered Sep 23 '22 08:09

Nick Tomlin


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)

like image 33
Yotam Omer Avatar answered Sep 23 '22 08:09

Yotam Omer