Pars Pars - 3 months ago 16
CSS Question

Change an element css while hovering on another element in css?

Is there any way to change an element's css while focusing or hovering on one of it's children?

Ex: while I move my mouse on A, B's background color changes.
if B is a descendant A, it is possible.

--A

-----B

using

#A:hover #B { background-color: blue }


DEMO




in sibling:

---A

---B

It is :
#A:hover ~ #B { background-color: blue; }


DEMO




assume B is a descendant of A.

what if I want to change #A background, while I am hovering on B. how could it be?

--A

-----B

Answer

Doing this in pure CSS is unfortunately not possible...at this time. However, there is supposedly an upcoming parent selector that would work well in this scenario. Click here for more info.

Work-around

In the meantime, you can also use javascript and/or jquery to accomplish this pretty easily.

DEMO

HTML

<div id="div1">
  div 1 area
  <p id="paragraph">
    This is paragraph
  </p>
</div>

CSS

#div1 {
  border:1px solid lightgray;
}
p {
  margin: 50px;
  background-color: lightblue;
  padding: 8px;
}

.altbg {
    background:grey;
}

jQuery

$(function(){
    $('#paragraph').mouseenter(function(){
        $(this).parent().addClass('altbg')
    }).mouseout(function(){
        $(this).parent().removeClass('altbg')
    });
});