使用 z-index 将前景元素移动到背景中的网格之前

Using z-index to move a foreground element before a grid in the background

在下面的示例中,我使用 class rowcell 创建了一个简单的网格,并希望使用 class 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>

您需要通过删除父元素上的 z-index 来建立新的 stacking context。此外,z-index 仅适用于定位元素,因此您需要在任务 div:

上设置 position: relative

.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>

另见 How to make child element higher z-index than parent?