简体   繁体   中英

Change another div background when hover over another div

Trying to change a div background color when hover over another div. But I can't get it to worked. Been seing aroud her now, but can't find a similair question.

<style type="text/css">
    #main {
        width: 960px;
        height: 600px;
        margin: auto;
        position: relative;
        background: red;
    }

    #trykk {
        width: 100px;
        height: 100px;
        background-color: yellow;
    }

    #trykk:hover #main {
        background-color: green;
    }
</style>

<div id="main">
    <div id="trykk">
    </div>
</div>

Thats the code I've been using. The only problem is that I'm not allowed to use javascript. So is there any way I can change background color on div #main when I hover over div #trykk?

A demo related to Rodik's answer, as he said you cannot change select parent using a child hence you cannot change the style of parent element, but if you want you can change your markup, as you said you cannot use javascript but if you can change the markup than it will go like this

Demo1

HTML

<div id="main">Main</div>
<div id="trykk">Trykk</div>

CSS

#main:hover + #trykk {
    background-color: green;
}

Or if you want to nest your div's as you are doing right now, just change the selector like this

Demo2

HTML

<div id="main">Main
<div id="trykk">Trykk</div>
</div>

CSS

#main:hover > #trykk {
    background-color: green;
}

CSS selection only works one way, from parent to child.

A child's state, hence, cannot affect it's parent's state.

A javascript mouseover event will be needed to implement this type of functionality.

with jquery you could do this:

$(function(){
    $("#trykk").hover(function(){
        $("#main").toggleClass("greenBackground");
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM