html - 使一个 div 填充剩余屏幕空间的高度

我正在开发一个 Web 应用程序,我希望内容填满整个屏幕的高度。

该页面有一个标题,其中包含一个 Logo 和帐户信息。这可以是任意高度。我希望内容 div 将页面的其余部分填充到底部。

我有一个标题 div 和一个内容 div。目前我正在使用这样的布局表格:

CSS 和 HTML

#page {
    height: 100%; width: 100%
}

#tdcontent {
    height: 100%;
}

#content {
    overflow: auto; /* or overflow: hidden; */
}
<table id="page">
    <tr>
        <td id="tdheader">
            <div id="header">...</div>
        </td>
    </tr>
    <tr>
        <td id="tdcontent">
            <div id="content">...</div>
        </td>
    </tr>
</table>

页面的整个高度被填满,不需要滚动。

对于内容 div 中的任何内容,设置 top: 0; 会将其放在标题的正下方。有时内容将是一个真实的表格,其高度设置为 100%。将 header 放入 content 将无法正常工作。

有没有不使用table也能达到同样效果的方法?

更新:

内容 div 中的元素也将高度设置为百分比。所以 div 内 100% 的东西会将其填充到底部。 50% 的两个元素也是如此。

更新 2:

例如,如果标题占据屏幕高度的 20%,则在 #content 内指定为 50% 的表格将占用 40% 的屏幕空间。到目前为止,将整个内容包装在一个表格中是唯一可行的方法。

最佳答案

2015 年更新:flexbox 方法

还有其他两个答案简要提及 flexbox ;但是,那是两年多以前的事了,他们没有提供任何示例。 flexbox 的规范现在肯定已经确定了。

Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status.

(taken from https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes)

所有主流浏览器和 IE11+ 都支持 Flexbox。对于 IE 10 或更早版本,您可以使用 FlexieJS shim。

要查看当前支持,您还可以在此处查看: http://caniuse.com/#feat=flexbox

工作示例

使用 flexbox,您可以轻松地在具有固定尺寸、内容尺寸尺寸或剩余空间尺寸的任何行或列之间切换。在我的示例中,我已将页眉设置为对齐其内容(根据 OPs 问题),我添加了一个页脚以显示如何添加固定高度区域,然后设置内容区域以填充剩余空间。

html,
body {
  height: 100%;
  margin: 0;
}

.box {
  display: flex;
  flex-flow: column;
  height: 100%;
}

.box .row {
  border: 1px dotted grey;
}

.box .row.header {
  flex: 0 1 auto;
  /* The above is shorthand for:
  flex-grow: 0,
  flex-shrink: 1,
  flex-basis: auto
  */
}

.box .row.content {
  flex: 1 1 auto;
}

.box .row.footer {
  flex: 0 1 40px;
}
<!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` -->

<div class="box">
  <div class="row header">
    <p><b>header</b>
      <br />
      <br />(sized to content)</p>
  </div>
  <div class="row content">
    <p>
      <b>content</b>
      (fills remaining space)
    </p>
  </div>
  <div class="row footer">
    <p><b>footer</b> (fixed height)</p>
  </div>
</div>

在上面的 CSS 中,flex属性简写 flex-grow , flex-shrink , 和 flex-basis属性来建立 flex 元素的灵 active 。 Mozilla 有一个 good introduction to the flexible boxes model .

https://stackoverflow.com/questions/90178/

相关文章:

javascript - 检索 HTML 元素的位置 (X,Y)

javascript - 在 jQuery 中创建一个 div 元素

javascript - 如何将一个元素移动到另一个元素中?

。使用哪个?">html -