我有以下HTML代码:
<html>
<body>
<h2>Title</h2>
<div id='large_div'>
blah.. blah.. blah..
</div>
</body>
</html>
我该如何让large_div
占据剩余的页面高度?
这是页面的CSS:
html { height: 100%; }
body { height: 100%; }
#large_div {
/* ??? */
}
您可以尝试在#large_div上设置一个负边距,该边距等于h2的高度。不幸的是,这不是非常稳定的代码,因为h2的高度会根据文本长度和浏览器而变化:
#large_div {
height: 100%;
margin-top: -1em; /* adjust to height of h2 */
}
$(document).ready(function(){
$('#large_div').css({height: $(window).height() - $('h2').height()});
});
所以,你基本上想要一个表格布局?这是 CSS 中最棘手的事情之一。你可以考虑回到老式的 HTML 表格,但如果你不关心 IE6/7支持,那么你也可以尝试使用 table
、table-row
和最终的 table-cell
的 display
属性进行调整。
这里有一个 SSCCE,复制粘贴并运行它。
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 3323454</title>
<style>
html {
height: 100%;
}
body {
display: table;
margin: 0;
width: 100%;
height: 100%;
}
#large_div {
display: table-row;
width: 100%;
height: 100%;
background: pink;
}
</style>
</head>
<body>
<h2>Title</h2>
<div id="large_div">blah.. blah.. blah..</div>
</body>
</html>
再次强调,这仅适用于支持CSS2标准的浏览器。
如果你只是想给div一个漂亮的背景,那么有更好的解决方案。
html,body {height:100%;border:0px;margin:0px;padding:0px;}
#large_div {height:100%;margin:0px;}
#topdiv { height:100px; }
#bottomdiv { height:100%; margin-bottom:-100px; bottom:0; }
很不幸,我现在所处的位置无法测试这个,所以可能会有偏差...但我相信我以前用过类似的东西,效果也差不多。
你可以通过调整这些CSS属性来找到解决方案,或者至少找到一个“足够好”的解决方案...
祝你好运!