Increase element's parent height (relative position) based on child's height (absolute position)

Viewed 418

How can I increase the height of the parent element which has relative position based on child elements height which has absolute position.

In my below example height of the .parent element is showing as 0px

PS: I do not want to use any script

Expected:

enter image description here

What I am getting:

enter image description here

jsFiddle

HTML:

<div class="parent">
    <div class="child" style="top:20px;">Hello</div>
    <div class="child" style="top:40px;">Some content</div>
    <div class="child" style="top:60px;">Some more content</div>
</div>

CSS:

.parent{position:relative;background:green;height:100%;border:1px solid #000000;width:250px;}
.child{position:absolute;}
2 Answers

This snippet gives you the look you want using CSS only.

It does this by making a pseudo element on the last child set a green background going a long way up, and making a pseudo element on the first child overwrite the bit that is above the overall element so it looks as though it isn't there.

The border is similarly hacked-in using the pseudo elements.

enter image description here

.parent {
  position: relative;
  width: 250px;
}

.child,
.child::before,
.child::after {
  box-sizing: border-box;
}

.child {
  position: absolute;
}

.child:first-child::before {
  content: '';
  position: absolute;
  bottom: 1em;
  background-color: white;
  width: 250px;
  height: 100vh;
  z-index: -1;
  border-bottom: 1px solid #000000;
}

.child:last-child::before {
  content: '';
  position: absolute;
  bottom: 0;
  background-color: green;
  width: 250px;
  height: 100vh;
  border: 1px solid #000000;
  border-top-width: 0;
  z-index: -2;
}
<div class="parent">
  <div class="child" style="top:20px;">Hello</div>
  <div class="child" style="top:40px;">Some content</div>
  <div class="child" style="top:60px;">Some more content</div>
</div>

What it does not do, and cannot do, is set the height of the parent. And there is an assumption that the background above the parent is white (it could have any color built in of course but it's not totally generalisable - more an exercise).

change height:100% to height:100px or as much as you want, in parent class

because absolute position hasn't any height you should define height for parent.

.parent{
    position:relative;
    background:green;
    height:100px;
    border:1px solid #000000;
    width:250px;
 }
Related