Search code examples
htmlcsspositionheightabsolute

How to set parent div's height as child div with position: absolute


I have parent div which has no height, there is also nested another child div with position absolute inside it. Child div has 652px of height. But I cannot get the same height in parent div. I tried to play with clear: both, overflow.

Here is the code:

HTML

    <div class="content">
      <div class="container">
          some other elements whose height is 652px... 
      </div>
     </div>

CSS

.content {
  position: relative;
}

.container {
  position: absolute;
  width: 100%;
  max-width: 1160px;
  margin: 0 auto;
  padding: 120px 0;
}

Content div's height is 0. Container div's height is 652px. How to make content div's height the same as container div's height?


Solution

  • I don't think this is possible with CSS while keeping the children absolutely positioned.

    Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.

    If you really had to achieve this affect while keeping the children as position: absolute, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.

    var content=document.querySelector('.content');
    var container=document.querySelector('.container');
    
    content.style.height=container.offsetHeight + 'px';
    *{box-sizing:border-box;}
    
    .content {
      width: 100%;
      max-width: 1160px;
      margin: 0 auto;
      /*padding: 120px 0;*//*Padding removed for example*/
       border:5px solid green;
    }
    .container{
      position: absolute;
      overflow: hidden;
      width: 100%;
      border:2px solid red;
      height:652px;
    }
    <div class="content">
      <div class="container">
        some other elements whose height is 652px...
      </div>
    </div>