Pars
Pars

Reputation: 5272

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

Upvotes: 2

Views: 3984

Answers (2)

CherryCo
CherryCo

Reputation: 1

It is actually possible in css. Somebody made this fiddle: http://jsfiddle.net/u7tYE/

#a:hover + #b {
        display:block;
        background-color:rgb(200,200,150);
    }
    #b{display:none;background-color:rgb(200,200,150;}
<a id="a">Menu</a>
<div id="b">
<p>Home</p>
<p>About</p>
<p>Login</p>
</div>

It works perfectly.

Upvotes: 0

Ross Brasseaux
Ross Brasseaux

Reputation: 4151

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')
    });
});

Upvotes: 3

Related Questions