简体   繁体   中英

Hover a specific div - Change another div

I want to change background color of a div when hovering on another one. The first div is going to be black, but not change when hover over. When hovering over the second div, the background on that is going to turn black, and the first div is going to turn white. I have done this before, but it seems like it doesn't work anymore.

CSS

.svart {
    background-color: black;
}

.hvit {
    background-color: white;
}

.hvit:hover {
    background-color: black;
}

HTML

 <div id="bestill_forside" class="svart">
    One
    </div>

    <div id="lear_forside" class="hvit">
    Two
</div>

I have tried the following:

.hvit:hover .svart {
        background-color: white;
}

.hvit:hover + .svart {
        background-color: white;
}

.hvit:hover > .svart {
        background-color: white;
}

.svart must be below .hvit in the document, you cannot select previous elements in CSS:

    <div id="lear_forside" class="hvit">
    Two
    </div>
    <div id="bestill_forside" class="svart">
    One
    </div>

What your CSS selectors were doing was:

.hvit:hover .svart {
        background-color: white; */This Selected .svart inside of .hvit*/
}

.hvit:hover + .svart {
        background-color: white; */This Selected .svart that was a immediate sibling of .hvit*/
}

.hvit:hover > .svart {
        background-color: white; */This Selected .svart that was a direct child of .hvit*/
}

Read more about CSS selectors:
http://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors

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