我正在尝试在元素悬停时为背景颜色设置动画,但我无法做到让文本始终可见/位于顶部。似乎设置 z-index 没有做任何事情。还有什么我应该尝试做的吗?
ul li {
background-color: #eee;
padding: 10px;
position: relative;
width: 200px;
}
ul li:hover .bg:before {
width: 50%;
}
.text {
z-index: 999999999;
color: #fff;
text-shadow: 1px 1px 1px #333;
display: inline-block;
}
.bg:before {
content: '\A';
position: absolute;
background: black;
top: 0;
bottom: 0;
left: 0;
width: 2%;
transition: all 2s;
}
<ul>
<li>
<div class="text">Hover over this text</div>
<div class="bg"></div>
</li>
</ul>
最佳答案
z-index
不会影响文本元素,因为它是静态定位的,而不是绝对定位的 bg 元素。要解决此问题,您可以将 position: relative;
添加到文本元素:
ul li {
background-color: #eee;
padding: 10px;
position: relative;
width: 200px;
}
ul li:hover .bg:before {
width: 50%;
}
.text {
z-index: 999999999;
color: #fff;
text-shadow: 1px 1px 1px #333;
display: inline-block;
position: relative;
}
.bg:before {
content: '\A';
position: absolute;
background: black;
top: 0;
bottom: 0;
left: 0;
width: 2%;
transition: all 2s;
}
<ul>
<li>
<div class="text">Hover over this text</div>
<div class="bg"></div>
</li>
</ul>
关于html - 如何在悬停时有不同的背景动画时始终显示文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42837900/