我正在尝试在元素悬停上为背景颜色设置动画,但我无法使其文本保持始终可见/在顶部。设置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>
答案 0 :(得分:3)
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>
答案 1 :(得分:1)
z-index
仅适用于定位元素,例如:
所以将position: relative;
添加到.text
类
ul li {
background-color: #eee;
padding: 10px;
position: relative;
width: 200px;
}
ul li:hover .bg:before {
width: 50%;
}
.text {
position: relative;
z-index: 2;
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>