2

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

9
  • 2
    You seem to be looking for a parent selector. If that is the case, it is not possible atleast until CSS4 comes. Commented Oct 3, 2013 at 15:11
  • 3
    ..And until then, Javascript is your best alternative. Commented Oct 3, 2013 at 15:12
  • possible duplicate of Change element style on hover another element Commented Oct 3, 2013 at 15:13
  • and How to change one element while hovering over another Commented Oct 3, 2013 at 15:14
  • 1
    @aliA: Ok, no issues :) I think there are already quite a few JS/jQuery based solutions in SO for the same topic if in case you need them :) Commented Oct 3, 2013 at 15:24

2 Answers 2

3

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')
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.