如何在不使用绝对定位的情况下将 div(不是视口的大小)拉伸到视口底部?
如果我使用绝对定位将我的“主” div 拉伸到视口的底部,那么主上方的任何新添加的元素,比如导航栏,都不会被浏览器自动重新定位,因为“主” div 与不再处于正常流程中。
如果我必须走绝对路线,我真的不想每次在正常流程中添加/删除动态 div(或其他包含)时都重新计算受影响元素的顶部和底部位置。
小提琴
HTML:
<div id="wrapper">
<div id="header">
HEADER<br>
<input id="btnNavBar" type="button" value="add/remove nav bar"/>
</div>
<div id="main">
MAIN CONTENT NEEDS TO STRETCH TO BOTTOM OF VIEWPORT, BUT NOT BE ABSOLUTE SO THAT IT WILL AUTOMATICALLY ADJUST FOR ANY NEWLY ADDED DYNAMIC ELEMENTS ABOVE IT SINCE IT'LL STILL BE IN THE NORMAL FLOW.
</div>
</div>
CSS:
html, body {
height: 100%;
margin: 0px;
}
#wrapper {
height: 100%;
background-color: black;
}
#header {
height: 50px;
text-align: center;
background-color: red;
}
#main {
background-color: gray;
height: 100%;
}
/* UNCOMMENT THIS SECTION TO MAKE THE STRETCHING WORK WITH ABSOLUTE POSITIONING,
BUT NOT FOR ANY NEWLY ADDED ELEMENTS */
/*#wrapper {
position: relative;
}
#main {
height: auto;
position: absolute;
bottom: 0px;
top: 50px;
}*/
JS:
$('#btnNavBar').click(function(){
var $navBar = $('#navBar');
if ($navBar.length == 0)
{
$('<div>').prop('id','navBar').css({'height':'20px',
'background-color':'yellow', 'text-align':'center'})
.text('Dynamically Added Nav Bar').insertAfter('#header');
}
else
$navBar.remove();
});