css – Z-index不适用于flex元素?

前端之家收集整理的这篇文章主要介绍了css – Z-index不适用于flex元素?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Flexbox,z-index & position: static: Why isn’t it working?1个
> Understanding z-index stacking order1个
我正在尝试有两列,一个是可以扩展并与另一列重叠的菜单.但我使用flex元素来包装这些列,我的菜单扩展到另一个元素后面,即使有更大的z-index.

渲染是这样的:

.main {
  font-family: 'Open Sans',Helvetica,sans-serif;
  display: flex;
  background-color: #99baef;
}

nav {
  height: 100%;
  width: 8em;
  background-color: black;
  z-index: 1;
}

.navBox {
  Box-sizing: border-Box;
  background-color: black;
  color: white;
  height: 4em;
  width: 100%;
  text-align: center;
  line-height: 4em;
  border-top: 1px dotted #99baef;
  transition: all 1s;
}

.navBox:hover {
  width: 130%;
  border-top: none;
  background-color: #4a77c4;
  color: black;
}

.container {
  padding: 1em;
}

a {text-decoration: inherit;}
<div class="main">
  <div class="maincolumn">
    <nav>
      <a href="">
        <div class="navBox">
          Nav 1
        </div>
      </a>
      <a href="">
        <div class="navBox">
          Nav 2
        </div>
      </a>
    </nav>
  </div>
  <div class="maincolumn">
    <div class="container">
      <h2>Title</h2>
      <p>This is a text.</p>
    </div>
  </div>
</div>

看到?扩展时,我希望我的菜单页面的其余部分重叠.我怎样才能做到这一点?

解决方法

Flex项目只是flex-container的直接子项.

Flex项目遵循z-index顺序,但您不是将z-index应用于flex-items而是应用于它们的后代.

w3c flexbox spec开始:

07001 paint exactly the same as inline blocks 07002,except that 07003-modified document order is used in place of raw document order,and 07004 values other than 07005 create a stacking context even if 07006 is 07007.

因此,为了使其工作,您应该将更大的z-index应用于您的第一个Flex项目.演示:

.main {
  font-family: 'Open Sans',sans-serif;
  display: flex;
  background-color: #99baef;
}

.maincolumn:first-child {
  z-index: 1;
}

nav {
  height: 100%;
  width: 8em;
  background-color: black;
}

.navBox {
  Box-sizing: border-Box;
  background-color: black;
  color: white;
  height: 4em;
  width: 100%;
  text-align: center;
  line-height: 4em;
  border-top: 1px dotted #99baef;
  transition: all 1s;
}

.navBox:hover {
  width: 130%;
  border-top: none;
  background-color: #4a77c4;
  color: black;
}

.container {
  padding: 1em;
}

a {text-decoration: inherit;}
<div class="main">
  <div class="maincolumn">
    <nav>
      <a href="">
        <div class="navBox">
          Nav 1
        </div>
      </a>
      <a href="">
        <div class="navBox">
          Nav 2
        </div>
      </a>
    </nav>
  </div>
  <div class="maincolumn">
    <div class="container">
      <h2>Title</h2>
      <p>This is a text.</p>
    </div>
  </div>
</div>

猜你在找的CSS相关文章