1

I would like to display some children div one above the other with a small offset. The picture below illustrates my expected result.

Expected result

In order, to make children div one above the other with a small offset, I set the position of the children div to absolute and it works. However, doing that the parent2 hides the parent1 (see the result of snippet code). This is due of the the position absolute set to children div.

.main {
  position: absolute;
  z-index: 500;
  left: 56px;
  display: block;
}

.parent {
  position: relative;
  margin: 10px;
}

.parent>* {
  position: absolute;
}

.parent>*:nth-of-type(1) {
  z-index: 10;
}

.parent>*:nth-of-type(2) {
  transform: translateY(1.4rem) scale(.95);
  z-index: 9;
}
<div class="main">
  <div id="parent1" class="parent">
    <div class="child" style="background-color:blue;"><br>Child1</div>
    <div class="child" style="background-color:red;"><br><br><br>Child2</div>
  </div>
  <div id="parent2" class="parent">
    <div class="child" style="background-color:green;"><br>Child1</div>
    <div class="child" style="background-color:yellow;"><br>Child2</div>
  </div>
</div>

The solution is to set a height to the parents div, but the height of the child is not always the same. I found linked issues but I would like to avoid to use JS.

PierBJX
  • 2,093
  • 5
  • 19
  • 50

1 Answers1

2

Use display:grid and make both elements on the same area and you will have the overlapping effect without position:absolute

.main {
  position: absolute;
  z-index: 500;
  left: 56px;
  display: block;
}

.parent {
  position: relative;
  margin: 10px;
  display:grid; /* here */
  align-items:start; /* disable stretch alignment */
}

.parent>* {
  grid-area:1/1; /* here */
}

.parent>*:nth-of-type(1) {
  z-index: 10;
}

.parent>*:nth-of-type(2) {
  margin-top:1.4rem; /* you can now use margin instead of translate */
  transform: scale(.95);
  z-index: 9;
}
<div class="main">
  <div id="parent1" class="parent">
    <div class="child" style="background-color:blue;"><br>Child1</div>
    <div class="child" style="background-color:red;"><br><br><br>Child2</div>
  </div>
  <div id="parent2" class="parent">
    <div class="child" style="background-color:green;"><br>Child1</div>
    <div class="child" style="background-color:yellow;"><br>Child2</div>
  </div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415