z-index - CSS z-index 与绝对位置

标签 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/

最佳答案

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

相关文章:

css - IE9 中的 z-index 无法正常工作

css - 是否有可能做一些与 css 定位相关的绝对相关的事情?

html - 绝对 child 的相对高度,有一个相对的 parent

OpenGL - GlVertex 相对/绝对位置

html - 如何创建一个从下面溢出的文本div

html - 在 pre 元素中时,是否可以让 HTML span 元素自动换行?

css - 在不使用 px 的情况下在右侧对齐的堆叠/覆盖 div

css - z-index 不适用于 safari

jquery - 这个站点如何在 flash/flex 中分层图像(这可以在常规 html/css 中完成)

html - IE8 中输入的 z 索引是怎么回事?