如何在鼠标悬停在子元素上时改变父元素的颜色

3
我有一个包含社交链接的div,当鼠标悬停在任何不同颜色的链接上时,我希望背景颜色填充整个div。
目前,只有锚文本下方的背景会改变。
我正在研究如何使用纯CSS填充整个父元素与子元素的背景颜色。

#social {
    width: 400px;
    height: 300px;
    position: relative;
    font-size: 36px;
    font-weight: bold;
    text-align: center;
}
a:link {
    text-decoration: none;
    transition: all .5s ease;
}
a:hover {
    color: white;
}
#facebook:hover {
    background: #3b5998;
}
#twitter:hover {
    background: lightblue;
}
#google-plus:hover {
    background: tomato;
}
#instagram:hover {
    background: lightgreen;
}
<div id="social">
               <a id="facebook" href="#"> <span>Facebook</span></a><br>
                <a id="twitter" href="#"> <span>Twitter</span></a><br>
                <a id="google-plus" href="#"> <span>Google plus</span></a><br>
                <a id="instagram" href="#"> <span>Instagram</span></a><br>
</div>

1个回答

5

乍一看,它似乎是更改父元素样式的另一次尝试,但有一种方式可以使用纯CSS实现该效果。

方法是使用锚点元素的::after伪选择器。我们需要将其定义为绝对定位,并设置为父元素的100%尺寸。此外,为了防止重叠的兄弟姐妹,我们需要减少伪选择器的z-index属性,以使其在文本下面呈现。

以下是代码片段:

#social {
    width: 400px;
    height: 300px;
    position: relative;
    font-size: 36px;
    font-weight: bold;
    text-align: center;
}
a::after{
    content: " ";
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
    border-radius: 20px;
    background: transparent;
    transition: background .5s ease;
}
a:link {
    text-decoration: none;
    transition: color .5s ease;
}
a:hover {
    color: white;
}
#facebook:hover::after {
    background: #3b5998;
}
#twitter:hover::after {
    background: lightblue;
}
#google-plus:hover::after {
    background: tomato;
}
#instagram:hover::after {
    background: lightgreen;
}
<div id="social">
               <a id="facebook" href="#"> <span>Facebook</span></a><br>
                <a id="twitter" href="#"> <span>Twitter</span></a><br>
                <a id="google-plus" href="#"> <span>Google plus</span></a><br>
                <a id="instagram" href="#"> <span>Instagram</span></a><br>
</div>


这比你之前的解决方案更好,因为它使用::after而不是另一个div - Ruan Mendes
@JuanMendes 谢谢您的建议。我甚至不知道SO上有问答模式。 - Banzay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接