css absolute 高度塌陷

position:absolute时,引起父元素高度塌陷,解决办法就是设置min-height

by jun wang

HTML

<div id="header">
  <span id="tip"></span>
  <button id="fix" onclick="fixCollapse()" >
  修复塌陷问题
  </button>
  <button id="fix" onclick="recovery()" >
  还原现场
  </button>
</div>
<div id="wrapper">
  <div id="content">
  虽然子元素有高度,但是父元素的高度为0,因为absolute会脱离当前文档流;虽然,子元素在父元素内,但是与父元素不在同一个文档流,所以不会撑起父元素,所以父元素高度为0;
  </div>
</div>

CSS

#wrapper{
  position:absolute;
  width:100%;
  top:100px;
  background-color:green;
}
.defaultHeight{
  min-height:calc(100% - 100px);
  
}
#header{
  height:100px;
  background-color:gray;
  
}
#content{
  position:absolute;
 
  
}

JavaScript

window.calHeight=function(){
var height = document.getElementById("wrapper").clientHeight;
document.getElementById("tip").innerText="wrapper的高度是"+height;

}

window.fixCollapse=function(){

	document.getElementById("wrapper").classList.add("defaultHeight");
  calHeight();
}

window.recovery=function(){
document.getElementById("wrapper").classList.remove("defaultHeight");
calHeight();
}
calHeight();