首页 > 解决方案 > 使用 z-index 将前景元素移动到背景中的网格之前

问题描述

在下面的示例中,我使用类创建了一个简单的网格,并希望使用跨越两个网格单元的rowcell来呈现元素task。我使用z-index: 2样式将任务带到顶部,但这似乎没有按预期工作,我仍然看到两个单元格之间的垂直网格。我的错误是什么?

<!DOCTYPE html>
<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <style>
    .row {
      height: 34px;
      display: flex;
      flex-direction: row;
    }
    .cell {
      border-style: solid;
      border-width: 1px 0 1px 1px;
      width: 60px;
      min-width: 60px;
      z-index: 1;
    }
    .last-cell {
      border-right-width: 1px;
    }
    .task {
      background-color: #3db9d3;
      height: 30px;
      width: 119px;
      margin: 1px 0 0 1px;
      z-index: 2;
    }
  </style>
</head>
<body>
  <div class="row">
    <div class="cell">
      <div class="task">Task</div>
    </div>
    <div class="cell last-cell"></div>
  </div>
</body>

标签: htmlcssz-index

解决方案


您需要通过删除父元素上的 z-index来建立新的堆叠上下文。此外,z-index 仅适用于定位元素,因此您需要position: relative在 Task div 上进行设置:

.row {
  height: 34px;
  display: flex;
  flex-direction: row;
}

.cell {
  border-style: solid;
  border-width: 1px 0 1px 1px;
  width: 60px;
  min-width: 60px;
}

.last-cell {
  border-right-width: 1px;
}

.task {
  background-color: #3db9d3;
  height: 30px;
  width: 119px;
  margin: 1px 0 0 1px;
  z-index: 2;
  position: relative;
}
<div class="row">
  <div class="cell">
    <div class="task">Task</div>
  </div>
  <div class="cell last-cell"></div>
</div>

另请参阅如何使子元素的 z-index 高于父元素?


推荐阅读