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

10

我有这段简化的代码:

This is a line of text<br/>
<div style="background-color: orange; height: 100%">And this is a div</div>
的高度最终将成为浏览器窗口客户区域高度的100%,加上文本行的高度后,会超过窗口高度,因此您需要滚动。

如何使

的高度等于浏览器窗口的高度 减去 文本行的高度?

或者换句话说,如何使

在垂直方向上占用所有自由空间,而不管其他DOM对象已经占用了多少空间?

3个回答

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>

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

这是一个关于IT技术的问题。我将尽力为您提供更好的翻译。

3
我不喜欢使用绝对定位,但这似乎是获得这个结果的唯一方法......真是个好例子。 - Yevgeny Simkin
4
再强调一遍,如果内容可以滚动,这种方法行不通。 - sproketboy
如果文本行被分成两行(调整窗口大小以使宽度不足以显示该行可能会导致此问题),那么它也无法正常工作。 - Hoffmann

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>

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

不带溢出隐藏的示例: http://jsbin.com/otaru5/2


2
我喜欢你的做法,因为它可能足够好来模拟OP的要求,但我想知道:如果橙色div实际上有内容怎么办?当容器白色部分的内容变得更大时,overflow:hidden将截断该内容... - Bazzz
如果内容溢出,则无法正常工作。没有滚动条,文本会超出浏览器窗口底部。 - sproketboy

0

使用display: table;可以相当优雅地完成,而无需知道任何显式高度值。

演示在这里: http://codepen.io/shanomurphy/pen/jbPMLX

html, body {
  height: 100%; // required to make .layout 100% height
}

.layout {
  display: table;
  width: 100%;
  height: 100%;
}

.layout__row {
  display: table-row;
}

.layout__cell {
  display: table-cell;
  vertical-align: middle;
}

.layout__cell--last {
  height: 100%; // force fill remaining vertical space
}

<div class="layout">
  <div class="layout__row">
    <div class="layout__cell">
      Row 1 content
    </div>
  </div>
  <div class="layout__row">
    <div class="layout__cell layout__cell--last">
      Row 2 fills remaining vertical space.
    </div>
  </div>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接