简体   繁体   中英

Why is General sibling combinator not always working?

I have four divs, and i want to change their width and height on hover so the one you are hovering over expands and all others shrink for how much hovered one expanded. I managed to get it working when i hover over first div, but when i try to do the same with other three nothing happens. My HTML:

<div  id="main">
        <div  id="mainOne">
            <h3>text</h3>
        </div>
        <div  id="mainTwo">
            <h3>text2</h3>
        </div>
        <div  id="mainThree">
            <h3>text3</h3>
        </div>
        <div  id="mainFour">
            <h3>text4</h3>
        </div>
    </div>

My CSS:

/* HOVER 1 */

#mainOne:hover{
width:748px;
height:600px;
}

#mainOne:hover + #mainTwo{
width:248px;
height: 600px;
}

#mainOne:hover ~ #mainThree{
height:200px;
}
#mainOne:hover ~ #mainFour{
height:200px;
}

/* END HOVER 1 */

/* HOVER 2 */
#mainTwo:hover{
width:748px;
height:600px;
}

#mainTwo:hover + #mainOne{
width:248px;
height: 600px;
}
#mainTwo:hover + #mainThree{
height:200px;
}
#mainTwo:hover ~ #mainFour{
height:200px;
}

/* END HOVER 2 */

So when i hover over mainOne, everything changes, but when i hover over mainTwo just mainTwo changes and messes up everything else. What am i doing wrong? Thanks.

CSS can only ( currently ) target elements that appear later in the DOM, therefore #mainTwo + #mainThree will work, but #mainTwo + #mainOne cannot.

To target previous siblings you'd have to wrap the siblings within another, parent, element and then style the previous siblings based on the hover of that parent.

div > div {
    border: 1px solid #000;
    padding: 0.5em 1em;
    width: 80%;
    margin: 0 auto;
    color: #f00;
}

#main:hover > div {
    width: 50%;
}

#main:hover > div:hover ~ div {
    width: 50%;
}

#main:hover > div:hover {
    width: 80%;
}

JS fiddle proof-of-concept

All your mainTwo rules with :hover use the adjacent sibling combinator.

Only #mainTwo + #mainThree can match as neither #mainOne or #mainFour are the next sibling to #mainTwo .

If you used the general sibling combinator ( ~ ) then you could match #mainFour too.

Since #mainOne precedes #mainTwo , you can't match it with a rule that depends on the existence of #mainTwo .

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