问题
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