How to style the parent element when hovering a child element?

前端 未结 8 2194
灰色年华
灰色年华 2020-11-22 05:57

I know that there does not exist a CSS parent selector, but is it possible to style a parenting element when hovering a child element without such a selector?

To giv

相关标签:
8条回答
  • 2020-11-22 06:41

    This solution depends fully on the design, but if you have a parent div that you want to change the background on when hovering a child you can try to mimic the parent with a ::after / ::before.

    <div class="item">
        design <span class="icon-cross">x</span>
    </div>
    

    CSS:

    .item {
        background: blue;
        border-radius: 10px;
        position: relative;
        z-index: 1;
    }
    .item span.icon-cross:hover::after {
        background: DodgerBlue;
        border-radius: 10px;
        display: block;
        position: absolute;
        z-index: -1;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        content: "";
    }
    

    See a full fiddle example here

    0 讨论(0)
  • 2020-11-22 06:41

    A simple jquery solution for those who don't need a pure css solution:

        $(".letter").hover(function() {
          $(this).closest("#word").toggleClass("hovered")
        });
    .hovered {
      background-color: lightblue;
    }
    
    .letter {
      margin: 20px;
      background: lightgray;
    }
    
    .letter:hover {
      background: grey;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="word">
      <div class="letter">T</div>
      <div class="letter">E</div>
      <div class="letter">S</div>
      <div class="letter">T</div>
    </div>

    0 讨论(0)
提交回复
热议问题