【问题标题】:How to change color of parent on hover the child element如何在悬停子元素时更改父元素的颜色
【发布时间】:2017-07-03 03:31:33
【问题描述】:

我有一个带有社交链接的 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>

【问题讨论】:

    标签: html css


    【解决方案1】:

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

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

    这是一个sn-p:

    #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>

    【讨论】:

    • 这甚至比your previous solution 更好,因为它使用::after 而不是另一个div
    • @JuanMendes 谢谢你的建议。我什至不知道SO上的问答模式。
    猜你喜欢
    • 1970-01-01
    • 2014-10-29
    • 2018-11-28
    • 2011-07-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多