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



在下面的示例中,我使用类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>

您需要通过删除父元素上的z索引来建立新的堆叠上下文。此外,z索引仅适用于已定位的元素,因此您需要在Taskdiv上设置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>

另请参见如何使子元素的z索引高于父元素?

最新更新