我有一个带有社交链接的 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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
乍一看,这似乎是另一种改变父元素样式的尝试,但有一种方法可以使用纯 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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)