Html – Change another div background when hover over another div

csshtml

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?

Best Answer

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;
}
Related Topic