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

时间:2010-05-24 15:47:45

标签: css html

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

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

6 个答案:

答案 0 :(得分:34)

你可以使用绝对定位。

<强> 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并指定top,right,bottom和left属性,就会得到占用整个视口的div。

然后,您将padding-top上的#content设置为&gt; = #header的高度。

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

我不确定浏览器的友好程度。查看this article at A List Apart了解详情。

答案 1 :(得分:10)

显然,实现它的方法是使用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对象。

答案 2 :(得分:8)

另一种未给出的解决方案是使用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之外的问题。

答案 3 :(得分:3)

如果你calculate the page position of the div element,你可以在不知道标题元素的情况下做到:

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

答案 4 :(得分:2)

我建议你试试jquery-layout插件。您将在链接上看到一系列演示和示例。

我不知道您是否熟悉JQuery或其他Javascript助手框架的概念,例如Prototype.jsMootools,但使用其中一个是至关重要的。它们隐藏了程序员与浏览器相关的大多数技巧,并且它们具有许多用于UI,DOM操作等的有用扩展。

答案 5 :(得分:0)

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