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

我的未来我决定 提交于 2020-01-23 17:56:06

问题


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?


回答1:


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>



回答2:


Please provide valid code when posting a question. The syntax on both your html and css is incorrect. (Missing {, : and ; in CSS, className should be class in HTML)

Once fixed your code works the way it should. A parent element positioned absolute will expand it's dimensions according to it's children so if a child is 652px the parent will expand to 652px. However if you specify overflow: hidden; like you did and specify a fixed width or height (which you did not) then the absolute element will hide any content that is outside the fixed width or height.



来源:https://stackoverflow.com/questions/51911553/how-to-set-parent-divs-height-as-child-div-with-position-absolute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!