4
votes

I am practicing my css using the hover when I notice this problem when I hover on top the color will change to blue and the middle will change to color red but when I hover to middle the middle changes the color to red but the top remains.

I tried to add a !important to the middle:hover but it didn't work. I also remove the + sign but i think it will not work since it should be on the same div for that to work.

why does the hover not working for the top div when middle div is hovered?

HTML

<div class="top">
    <p> HELLO WORLD </p>
</div>

<div class="middle">
    <p> HELLO PEOPLE </p>
</div>

CSS

.top:hover + .middle {
    color:red;
}

.top:hover {
    color:blue;
}

.middle:hover {
    color:red;
}

.middle:hover + .top {
    color: blue;
}

FIDDLE HERE

2
You can't do this in CSS unfortunately. You will need javascript. - dfsq
any idea about + operator in CSS?? - Suresh Ponnukalai
+ is not working. you have to use javascript 4 that. - brandelizer
.middle:hover + .top means .top element after .middle, not before. - dfsq
+ selects the element (matching the second part of the selector, after +) that immediately follows the element matching the first part and is a sibling (not a child). Refer the specification here. Sample Fiddle where .middle:hover + .top will work. - Harry

2 Answers

0
votes

You cannot select a parent element in CSS unfortunately. But JavaScript can be used to resolve this problem.

Check out this for more info on selectors...http://www.w3.org/TR/CSS21/selector.html

0
votes

The CSS + selector is the next sibling selector. It doesn't work on previous siblings, similar to how you can't target a parent from a child. This is because CSS works Top-Bottom, (ie parent > child, next sibling etc) and not vice versa.

This article explains why CSS doesn't have a parent selector but same logic applies for the lack of previous sibling selectors.

tldr: Bottom-Up CSS selectors are not feasible because of their performance implications in browsers.