Can I use img:hover to get another element?

前端 未结 5 1525
青春惊慌失措
青春惊慌失措 2021-01-25 10:33

So is it possible to make this work

#element img:hover #otherelement {...}

like

#element:hover #otherelement {...}
5条回答
  •  旧巷少年郎
    2021-01-25 11:22

    What you can do is selecting next element(s) by:

    Adjacent sibling combinator

    element1 + element2 Selects every element2 element that are placed immediately after element1 element(s). They're siblings.

    #element img:hover + #otherelement
    

    If the #otherelement is placed right after img, it'll be selected when img is hovered.

    Another option is:

    General sibling combinator

    element1 ~ element2 Matches occurrences of element2 that are preceded by element1 while they have the same parent. They're siblings too, but element2 doesn't have to be immediately preceded by element1.

    #element img:hover ~ #otherelement
    

    If #otherelement and img are siblings, and #otherelement is placed somewhere after the img, it'll be selected when img is hovered.

    Here is an example

    HTML

    Sport
    This is a text.

    CSS:

    #parent {
      overflow: hidden;
      width: 200px;
      height: 200px;
    }
    
    .text {
      position: relative;
      -webkit-transition: .3s all;
      -moz-transition: .3s all;
      transition: .3s all;
      background-color: rgba(255,255,255,.5);
      height: 40px;
      line-height: 40px;
    }
    
    #parent img:hover + .text {
      top: -40px;
    }
    

提交回复
热议问题