使DIV垂直填充页面的其余部分?

我有一个占用大部分页面的Google地图应用程序。 不过,我需要为菜单栏预留最顶层的空间。 如何使地图div自动填充其垂直空间? height: 100%不起作用,因为顶部栏会将地图推过页面底部。

 +--------------------------------+ | top bar (n units tall) | |================================| | ^ | | | | | div | | (100%-n units tall) | | | | | v | +--------------------------------+ 

你可以使用绝对定位。

HTML

 <div id="content"> <div id="header"> Header </div> This is where the content starts. </div> 

CSS

 BODY { margin: 0; padding: 0; } #content { border: 3px solid #971111; position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-color: #DDD; padding-top: 85px; } #header { border: 2px solid #279895; background-color: #FFF; height: 75px; position: absolute; top: 0; left: 0; right: 0; } 

通过绝对定位#content并指定顶部,右侧,底部和左侧属性,您将获得占据整个视口的div。

然后你将#content上的padding-top设置为> = #header

最后,将#header放在#content并将其绝对定位(指定顶部,左侧,右侧和高度)。

我不确定这是如何浏览器友好。 查看A List Apart上的这篇文章了解更多信息。

显然,这样做的方式是使用JavaScript来监视onload和onresize事件,并以编程方式调整填充div的大小,如下所示:

使用jQuery:

 function resize() { $("#bottom").height($(document).height() - $('#top').height()); } 

使用普通的JavaScript:

 function resize() { document.getElementById("bottom").style.height = (document.body.clientHeight - headerHeight) + "px"; } 

编辑:然后将这些绑定到window对象。

没有给出的另一个解决scheme使用CSS3而不是JavaScript。 现在有一个calc()函数可以用来做同样的事情:

HTML

 <div id="content"> <div id="header"> Header </div> <div id="bottom"> Bottom </div> </div> 

CSS3

 #content { height: 300px; border-style: solid; border-color: blue; box-sizing: border-box; } #header { background-color: red; height: 30px; } #bottom { height: calc(100% - 30px); background-color: green; } 

这是jsfiddle

您可能还需要考虑使用box-sizing: border-box样式的内部div,因为这样可以消除填充和边界在父div之外的问题。

如果你计算div元素的页面位置,你可以不需要知道头元素:

 function resize() { var el = $("#bottom"); el.height($(document).height() - el.offset().top); } 

我build议你尝试jQuery的布局插件。 你会看到一连串的演示和链接的例子。

我不知道你是否熟悉JQuery或其他一些Javascript helper框架的概念,比如Prototype.js或者Mootools,但是使用其中的一个很重要。 它们隐藏了程序员大多数浏览器相关的技巧,并且对UI,DOM操作等有很多有用的扩展。

嗯,你需要添加html, body { height: 100%; } html, body { height: 100%; } ,在此之后,一个relative元素, min-height: 100%

之后,对于IE6

 <!--[if lt IE 7]> <style media="screen" type="text/css"> MyAutoheightElement { height: 100%; } </style> <![endif]--> 

这将使您的网站在每个浏览器中达到100%的高度。
尝试一下! 我希望它有助于:)

 var sizeFooter = function(){ $(".webfooter").css("padding-bottom", "0px").css("padding-bottom", $(window).height() - $("body").height()) } $(window).resize(sizeFooter);