Search code examples
htmlcssz-index

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


In the following example I create a simple grid using the class row and cell and would like to render the element with class task spanning over two grid cells. I use z-index: 2 style to bring the task to the top but this does not seem to work as expected and i still see the vertical grid between two cells. What is my mistake?

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


Solution

  • You need to establish a new stacking context by removing the z-index on the parent element. Also, the z-index only applies to positioned elements so you need to set position: relative on the 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>

    See also How to make child element higher z-index than parent?