我有一个问题,我有两个div:
<div style="width:100%; height:50px;" id="div1"></div>
<div style="width:100%;" id="div2"></div>
如何让 div2 占据页面的剩余高度?
使用绝对定位:
#div1{
width: 100%;
height: 50px;
background-color:red;/*Development Only*/
}
#div2{
width: 100%;
position: absolute;
top: 50px;
bottom: 0;
background-color:blue;/*Development Only*/
}
<div id="div1"></div>
<div id="div2"></div>
您可以使用此http://jsfiddle.net/Victornpb/S8g4E/783/
#container {
display: table;
width: 400px;
height: 400px;
}
#container > div{
display: table-row;
height: 0;
}
#container > div.fill{
height: auto;
}
只需将类.fill
应用于任何子元素,即可使其占用剩余的高度。
<div id="container">
<div>
Lorem ipsum
</div>
<div>
Lorem ipsum
</div>
<div class="fill"> <!-- this will fill the remaining height-->
Lorem ipsum
</div>
</div>
它适用于您想要的任何孩子,无需额外标记。
<table>
不应用于布局。display: table
提供了一种类似的行为方式,而不涉及相同的语义。 - herman一种方法是将div设置为position:absolute
,并将其顶部设为50像素,底部设为0像素;
#div2
{
position:absolute;
bottom:0px;
top:50px
}
既然你知道前面的内容占据了多少像素,那么你可以使用calc()
函数:
height: calc(100% - 50px);
我自己也面临同样的挑战,使用 flex
属性找到了以下这两个答案。
CSS
.container {
display: flex;
flex-direction: column;
}
.dynamic-element{
flex: 1;
}
使用CSS表格,您可以在两个div周围包装一个div,并使用此css/html结构:
<style type="text/css">
.container { display:table; width:100%; height:100%; }
#div1 { display:table-row; height:50px; background-color:red; }
#div2 { display:table-row; background-color:blue; }
</style>
<div class="container">
<div id="div1"></div>
<div id="div2"></div>
</div>
取决于哪些浏览器支持这些显示类型,不过我认为IE8及以下版本不支持。编辑:撤回-- IE8支持CSS表格。
//Credit Efy Teicher
$(document).ready(function () {
$(".fillHight").fillHeight();
$(".fillWidth").fillWidth();
});
window.onresize = function (event) {
$(".fillHight").fillHeight();
$(".fillWidth").fillWidth();
}
$.fn.fillHeight = function () {
var siblingsHeight = 0;
this.siblings("div").each(function () {
siblingsHeight = siblingsHeight + $(this).height();
});
var height = this.parent().height() - siblingsHeight;
this.height(height);
};
$.fn.fillWidth = function (){
var siblingsWidth = 0;
this.siblings("div").each(function () {
siblingsWidth += $(this).width();
});
var width =this.parent().width() - siblingsWidth;
this.width(width);
}
* {
box-sizing: border-box;
}
html {
}
html, body, .fillParent {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="fillParent" style="background-color:antiquewhite">
<div>
no1
</div>
<div class="fillHight">
no2 fill
</div>
<div class="deb">
no3
</div>
</div>
calc
函数来计算第二个*{
box-sizing: border-box;
}
#div1{
height: 50px;
background: skyblue;
}
#div2{
height: calc(100vh - 50px);
background: blue;
}
<div id="div1"></div>
<div id="div2"></div>
<div>
<div id="header">header</div>
<div id="content">content</div>
<div id="footer">footer</div>
</div>
#header {
height: 200px;
}
#content {
height: 100%;
margin-bottom: -200px;
padding-bottom: 200px;
margin-top: -200px;
padding-top: 200px;
}
#footer {
height: 200px;
}
#div2
内部内容比窗口更高时会发生什么? - thirtydot