riogrande
riogrande

Reputation: 349

Change other children when hovering nth-child(1)

I have 4 divs (.box) that are children of one parent div (.cont)

CSS

.cont{
    width: 100%;
    height: auto;
}
.box{
    width: 25%;
    color: #fff;
    text-align: center;
    padding: 50px 0;
    background: #333;
    float: left;
}

HTML

<div class="cont">
    <div class="box">
        aaa
    </div>
    <div class="box">
        aaa
    </div>
    <div class="box">
        aaa
    </div>
    <div class="box">
        aaa
    </div>
</div>

What I want to do is: when I hover any one child, all the other children should change.

First I tried this method:

.box:nth-child(1):hover .box:not(:nth-child(1)) {
    background:#ccc;
}

But I can't use this because box is not parent of box, they are same level elements.

Then I tried with sibiling selector:

.box:nth-child(1):hover ~ .box:not(:nth-child(1)) {
    background:#ccc;
}
.box:nth-child(2):hover ~ .box:not(:nth-child(2)) {
    background:#ccc;
}
.box:nth-child(3):hover ~ .box:not(:nth-child(3)) {
    background:#ccc;
}
.box:nth-child(4):hover ~ .box:not(:nth-child(4)) {
    background:#ccc;
}

But problem is that sibling selector only works with next siblings (next child), on my example everything is working perfectly for .box:nth-child(1):hover all others are changing background. But for .box:nth-child(2):hover only 3 and 4 change style because there is no previous sibling selector, so same results for 3 and 4.

Is there any way to do this with only CSS or will I have to use jQuery?

Upvotes: 0

Views: 1571

Answers (2)

Fastmover
Fastmover

Reputation: 260

Move the Background color to the outer DIV, then do the on hover on it change the background to grey, while doing the active box being hovered over to the darker color you want. See example:

http://jsfiddle.net/fastmover/26pvgbsb/

.cont {
    background-color: #333333;
    width: 100%;
    height: auto;
    overflow: hidden;
}
.box {
    width: 25%;
    color: #fff;
    text-align: center;
    padding: 50px 0;
    float: left;
}
.cont:hover {
    background:#ccc;
}
.box:hover {
    background: #333;
}

Upvotes: 0

pawel
pawel

Reputation: 36995

.cont:hover > * {
    background:#ccc;   // make all childern of .cont #ccc
}
.cont:hover > *:hover {
    background:#333;   // revert the hovered child to #333
}

http://jsfiddle.net/o71hp1q4/

Or even simpler:

/* selects all children of the hovered element that are not hovered theselves */
.cont:hover > *:not(:hover) {  
    background:#ccc;   
}

http://jsfiddle.net/o71hp1q4/1/

Upvotes: 5

Related Questions