如何在不使用绝对定位的情况下将div(不是视口的大小)拉伸到视口底部?
如果我使用绝对定位将“main”div拉伸到视口的底部,那么任何新添加的元素(例如导航栏)都不会被浏览器自动重新定位,因为“main” “div不再处于正常流动状态。
而且我真的不想重新计算top&每当我在正常流程中添加/删除动态div(或其他包含)时,受影响元素的底部位置,如果我必须使用绝对路径。
fiddle
的 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();
});
答案 0 :(得分:2)
将此添加到 CSS
#wrapper:before
{
content: '';
float: left;
height: 100%;
}
#main:after
{
content: '';
display: block;
clear: both;
}
并从height:100%
#main
经过测试: IE10,IE9,IE8,FF,Chrome。