CSS:高度 - 填写div的其余部分?

mat*_*att 34 css height

我想知道这是否可能与简单的CSS或如果我必须使用javascript为此?

我的网站上有一个侧边栏.一个简单的div#sidbar它通常高约1024px,但由于它的内容,高度会动态变化.

让我们想象一下以下情况:

<div id="sidebar">
   <div class="widget"></div> //has a height of 100px
   <div class="widget"></div> //has a height of 100px
   <div id="rest"></div> //this div should have the rest height till to the bottom of the sidebar
</div>
Run Code Online (Sandbox Code Playgroud)

我希望div#rest填充侧边栏的其余部分,直到它到达div#sidebar的底部.

纯css有可能吗?

小智 35

如果您知道#widget(在您的情况下为100px)的确切高度,则可以通过使用绝对定位来避免使用JavaScript:

#sidebar
{
height: 100%;
width: ...;
position: relative;
}

.widget
{
height: 100px;
}

#rest
{
position: absolute;
left: 0;
width: 100%;
top: 200px;
bottom: 0;
}
Run Code Online (Sandbox Code Playgroud)

  • http://blog.stevensanderson.com/2011/10/05/full-height-app-layouts-a-css-trick-to-make-it-easier/上有一个很好的演示.这种技术甚至适用于IE7. (6认同)

cas*_*nca 7

你想要的是类似100% - 200px但CSS不支持这些表达式.IE有一个非标准的"表达式"功能,但如果你希望你的页面可以在所有浏览器上运行,我就看不到没有JavaScript的方法.或者,你可以使所有div的使用百分比高度,所以你可以有10%-10%-80%的东西.

更新:这是一个使用JavaScript的简单解决方案.只要侧边栏中的内容发生变化,只需调用此函数:

function resize() {
  // 200 is the total height of the other 2 divs
  var height = document.getElementById('sidebar').offsetHeight - 200;
  document.getElementById('rest').style.height = height + 'px';
};
Run Code Online (Sandbox Code Playgroud)

  • 使用[`calc`](https://developer.mozilla.org/en-US/docs/CSS/calc)CSS值可以实现"100% - 200px". (14认同)

小智 6

我建议使用表元素作为替代:

  • +:干净的CSS
  • +:避免使用JavaScript
  • -:表在语义上被滥用
  • -:不是要求的div元素