manage event on parent>child hover css

61 views Asked by At

I have this html code

<article>
    <div class="a">
        <div class="a_b"></div>
    </div>
    <div class="c"></div>
</article>

I need to do some changes to div .c on div .a_b hover Can I do this using scss (or native css), without using any javascript code?

1

There are 1 answers

2
Rounin On

You can deploy the :hover pseudo-class (and other pseudo-classes like :focus, :checked, :target etc.) to modify the styles on:

  • the element itself
  • a descendant of that element
  • a subsequent sibling of the element.

In this setup:

<article>
    <div class="a">
        <div class="a_b"></div>
    </div>
    <div class="c"></div>
</article>

You can apply a pseudo-element to .a and it could modify the styles on .a (itself), .a_b (its child) or .c (its sibling).

But a pseudo-element on either .a_b or .c can't modify the styles on any element except the element itself - because neither element has any children or any subsequent siblings.


The solution:

In your structure, add .a_b as a subsequent sibling of .a:

<article>
    <div class="a">
    </div>
    <div class="a_b"></div>
    <div class="c"></div>
</article>

and then use CSS positioning to re-position .a_b so that visually, it appears to be inside .a (even though it is actually a sibling element of .a, rather than a child element of .a).