CSS z-index,位置绝对

时间:2015-12-29 12:26:38

标签: z-index absolute

我有简单的代码

问题是红色的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>

https://jsfiddle.net/24qbyh4p/

1 个答案:

答案 0 :(得分:2)

解决方案是将.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>