我有简单的代码
问题出在红色 div 上。它是动画的,但它的 z-index 大于它的父级,因此在动画时它会遮盖主 div。当我给动画 div z-index: -1 但 :hover 无法正常工作(动画 div 消失)时,我可以解决这个问题。有人可以帮忙吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.main {
width: 100px;
height: 100px;
background: green;
position: relative;
}
.main .bar {
height: inherit;
width: 300px;
position: absolute;
background: red;
left: -300px;
}
.main:hover .bar {
left: 100px;
transition: left .3s;
}
</style>
</head>
<body>
<div class="main"><div class="bar"></div></div>
</body>
</html>
最佳答案
解决方案是将 .main
的内容包装在一个 z-index
大于 .bar
的内部容器中。
.main {
width: 100px;
height: 100px;
position: relative;
}
.main > .bar {
height: inherit;
width: 300px;
position: absolute;
background: red;
left: -300px;
}
.main > .content {
height: 100%;
background: green;
position: relative;
z-index: 1;
}
.main:hover .bar {
left: 100px;
transition: left .3s;
}
<div class="main">
<div class="bar"></div>
<div class="content"></div>
</div>
关于z-index - CSS z-index 与绝对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34511038/