即使没有内容,如何强制DIV块扩展到页面底部?

时间:2020-03-06 14:51:38  来源:igfitidea点击:

在下面显示的标记中,我试图使内容div一直延伸到页面底部,但是只有在要显示内容的情况下才拉伸。我要执行此操作的原因是,即使没有任何内容要显示,垂直边框仍会在页面下方显示。

这是我的HTML:

<body>
    <form id="form1">
    <div id="header">
        <a title="Home" href="index.html" />
    </div>

    <div id="menuwrapper">
        <div id="menu">
        </div>
    </div>

    <div id="content">
    </div>

而我的CSS:

body {
    font-family: Trebuchet MS, Verdana, MS Sans Serif;
    font-size:0.9em;
    margin:0;
    padding:0;
}
div#header {
    width: 100%;
    height: 100px;
}
#header a {
    background-position: 100px 30px;
    background: transparent url(site-style-images/sitelogo.jpg) no-repeat fixed 100px 30px;
    height: 80px;
    display: block;
}
#header, #menuwrapper {
    background-repeat: repeat;
    background-image: url(site-style-images/darkblue_background_color.jpg);
}
#menu #menuwrapper {
    height:25px;
}
div#menuwrapper {
    width:100%
}
#menu, #content {
    width:1024px;
    margin: 0 auto;
}
div#menu {
    height: 25px;
    background-color:#50657a;
}

解决方案

你可以用最小高度声明来破解它

<div style="min-height: 100%">stuff</div>

我们也可能会这样:http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm

它不是我们所要求的,但是它也可能满足需求。

尝试使用以下css规则:

#content {
    min-height: 600px;
    height: auto !important;
    height: 600px;
}

更改高度以适合页面。为了跨浏览器兼容性,两次提到了height。

并非所有浏览器都支持min-height属性。如果我们需要#content来扩展它在较长页面上的高度,height属性将使其缩短。

这有点hack,但是我们可以添加一个空的div,其宽度为1px,高度为例如#content div内为1000像素。这将迫使内容至少高出1000像素,并在需要时仍允许更长的内容来扩展高度

我没有代码,但是我知道我曾经使用height:1000px和margin-bottom:-1000px;的组合来做到这一点。试试看

尽管它不如纯CSS优雅,但少量的javascript可以帮助实现这一点:

<html>
<head>
<style type='text/css'>
    div {
        border: 1px solid #000000;
    } 
</style>
<script type='text/javascript'>

    function expandToWindow(element) {
         var margin = 10; 

         if (element.style.height < window.innerHeight) { 
            element.style.height = window.innerHeight - (2 * margin) 
         }
    }

</script>
</head>
<body onload='expandToWindow(document.getElementById("content"));'>
<div id='content'>Hello World</div>
</body>
</html>

根据布局的工作方式,我们可能不愿意在&lt;html>元素上设置背景,该元素始终至少是视口的高度。

问题不是div不在100%的高度,而是它周围的容器不在高度,这在我怀疑我们正在使用的浏览器中会有所帮助:

html,body { height:100%; }

我们可能还需要调整填充和边距,但这将为我们提供90%的效果。如果需要使其与所有浏览器一起使用,我们将不得不对其进行一些调整。

这个站点有一些很好的例子:

http://www.brunildo.org/test/html_body_0.html
http://www.brunildo.org/test/html_body_11b.html
http://www.brunildo.org/test/index.html

我还建议转到http://quirksmode.org/

尝试瑞安·菲特(Ryan Fait)的"粘性页脚"解决方案,

http://ryanfait.com/sticky-footer/
http://ryanfait.com/resources/footer-stick-to-bottom-of-page/

可以在IE,Firefox,Chrome,Safari和据说的Opera中运行,但尚未进行测试。这是一个很好的解决方案。实施起来非常容易和可靠。