且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在悬停多个子元素时设置父元素的背景?

更新时间:2023-01-16 11:12:09

If you set the parent position: relative, it will contain any position: absolute children.

Create a new element inside the end of the parent, then make it position: absolute and position and size it so that it fills the parent.

Then use z-index: -1 to set it behind the rest of the content (e.g. the buttons).

Then you can use the General Sibling Combinator (~) to select the new element after the hovered element.

.facebook:hover ~ .background { background-color: rgb(50, 100, 150); }
.twitter:hover  ~ .background { background-color: rgb(50, 150, 250); }
.google:hover   ~ .background { background-color: rgb(250, 75, 50);  }

.share {
    position: relative;
}
.background {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
}                                                                                                                                                    /* Following styling for demo purposes only, not relevant */ .facebook:before { background-position:-46px -28px; width:101px; } .twitter:before { background-position:-151px -28px; width:90px; } .google:before { background-position:-245px -28px; width:94px; } .button:before { display:inline-block; content: ""; height:36px; background-image:url("http://i.stack.imgur.com/AXvMk.png"); border-radius: 3px; box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.2); } .button { display:inline-block; padding: 2px; } .white-container { padding: 10px 20px; font-size: 0; background: #fff; border-radius: 3px; } .background { background: #fff; } body { margin: 0 4px; border: 1px solid #aaa; border-top: 0px; box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.1) } .share { padding: 10px 15px; box-shadow: 0px 5px 5px -5px rgba(0,0,0,0.3) inset } body:before { content: ''; height: 4px; display: block; background: #fff; border-bottom: 1px solid #aaa } html { background: #efefef }

<div class="share">
    <div class="white-container">
      <a href="#" class="button facebook"></a>
      <a href="#" class="button twitter"></a>
      <a href="#" class="button google"></a>
      <div class="background"></div>
    </div>
</div>