Use :hover to modify the css of another class?

前端 未结 5 700
旧时难觅i
旧时难觅i 2020-11-29 01:44

Is there a way to modify the css for one class when hovering on an element from another class using only css ?

Something like:

.item:hover .wrapper {         


        
5条回答
  •  星月不相逢
    2020-11-29 02:40

    There are two approaches you can take, to have a hovered element affect (E) another element (F):

    1. F is a child-element of E, or
    2. F is a later-sibling (or sibling's descendant) element of E (in that E appears in the mark-up/DOM before F):

    To illustrate the first of these options (F as a descendant/child of E):

    .item:hover .wrapper {
        color: #fff;
        background-color: #000;
    }​
    

    To demonstrate the second option, F being a sibling element of E:

    .item:hover ~ .wrapper {
        color: #fff;
        background-color: #000;
    }​
    

    In this example, if .wrapper was an immediate sibling of .item (with no other elements between the two) you could also use .item:hover + .wrapper.

    JS Fiddle demonstration.

    References:

    • CSS 2.1 selectors, at the W3.org.

提交回复
热议问题