如何使DIV填充浏览器窗口的剩余垂直空间?

Pet*_*uza 9 html css

我有这个简化的代码:

This is a line of text<br/>
<div style="background-color: orange; height: 100%">And this is a div</div>
Run Code Online (Sandbox Code Playgroud)

div高度最终是浏览器窗口客户端空间高度的100%,它与文本行的高度相加,大于窗口高度,因此您必须滚动.

如何设置div高度,使浏览器窗口的高度减去文本行?

或者,换句话说,我如何让div垂直占用所有其他DOM对象已经占用的空间?

小智 6

我也遇到了同样的问题.这是我找到的解决方案:

<style>
.container{
    position: relative;
    height: 100%;
}
.top-div{
    /* height can be here. if you want it*/
}
.content{
    position:absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 1em; /* or whatever height of upper div*/
    background: red;
}
</style>
<div class="container">
    <div class="top-div">This is a line of text</div>
    <div class="content">And this is a div</div>
</div>
Run Code Online (Sandbox Code Playgroud)

来源 - http://www.codingforums.com/archive/index.php/t-142757.html

  • 我讨厌使用绝对定位,但这似乎是获得这个结果的唯一方法......非常好的例子. (3认同)
  • 再次.如果内容滚动,这将不起作用. (3认同)

Sha*_*haz 5

最终,你会想拥有一个容器."overflow:hidden"将隐藏任何溢出容器的东西.如果我们没有使用那个,那么我们会看到你上面提到的关于"......超过窗口高度,所以你必须滚动"的问题.

  <div id="container" style="color:white;height:500px;background-color:black;overflow:hidden;">
    This is the container
    <div style="height:100%;background-color:orange;">
      This div should take the rest of the height (of the container).
    </div>
  </div>
Run Code Online (Sandbox Code Playgroud)

隐藏溢出的示例:http://jsbin.com/oxico5

没有溢出隐藏的示例:http://jsbin.com/otaru5/2

  • 我喜欢你的方法,因为它可能足以模拟OP的要求,但我想知道:如果橙色div实际上有内容怎么办?当容器的白色部分的内容变大时,该内容将被`overflow:hidden`"切断".... (2认同)