richie_south
richie_south

Reputation: 53

CSS special hover

http://jsfiddle.net/98bzqoq1/

Is there any way to make a hover effect on Class="c" so it affects the background color on Class="d"

// My code so far

<div>
    <ul>
        <li class="c">Caroline</li>
        <li class="c">Emilia</li>
    </ul>
</div>
<div class="d">This text should be in a green box...</div>

// does not work

.c:hover ~ .d {
    background: lightgreen;
}

Upvotes: 0

Views: 227

Answers (2)

Woodrow Barlow
Woodrow Barlow

Reputation: 9047

Using pseudo-classes as an action to modify other elements can only be done if the other elements are direct or indirect siblings or children of the element which has the pseudo-class (such as :hover or :focus). The reason for this is because CSS child/sibling selectors are fairly restrictive.

You can use the > selector to select a direct child, the + selector to select an adjacent sibling, and the ~ selector to select a general subsequent sibling. For example, if you have the following HTML:

<div>
    <div class="c">Hover Me!</div>
    <div>
        This is a direct adjacent sibling to the element with class "c".
    </div>
</div>
<div class="d">
    This is an arbitrary element. It is neither a child nor sibling of 
    an element with class "c". It cannot be selected as a result of a 
    pseudo-class action on the textfield using CSS, but can be selected 
    using client-side scripting such as JavaScript or jQuery.
</div>

You could style the adjacent sibling to div class="c" with CSS, but there is no possible way to style the arbitrary paragraph as a result of div class="c" being hovered (because it is neither a child nor sibling, it is the sibling of a parent) without using client-side scripting (JavaScript, jQuery, etc.).

Using the jQuery .hover() functions, you can achieve your end goal. For example, the following code would style the arbitrary paragraph, and can be changed to select any element on the page (simply pass the element's CSS selector as an argument to the $() function):

$(".c").hover(function() {
    $(".d").css("background-color","green");
}, function() {
    $(".d").css("background-color","transparent");
});

Here is an example which demonstrates both the CSS and jQuery methods.

Upvotes: 0

Huangism
Huangism

Reputation: 16438

From your provided code you could do this, since the only content in your div is your list

div:hover ~ .d {
    background: lightgreen;
}

http://jsfiddle.net/98bzqoq1/1/

However, if your code is more complicated then this is not possible with the use of CSS only

Upvotes: 2

Related Questions