简体   繁体   中英

Make parent div height according to children absolute div

I would like to display some children div one above the other with a small offset. The picture below illustrates my 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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM