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

时间:2010-08-05 02:23:36

标签: 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>

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

纯css可以吗?

7 个答案:

答案 0 :(得分:35)

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

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

.widget
{
height: 100px;
}

#rest
{
position: absolute;
left: 0;
width: 100%;
top: 200px;
bottom: 0;
}

答案 1 :(得分: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';
};

答案 2 :(得分:6)

我建议将table-element作为替代方案:

  • +:clean CSS
  • +:避免使用javascript
  • - :表语义滥用
  • - :不是请求的div-elements

答案 3 :(得分:4)

我在寻找类似问题的答案时遇到了这个问题,我想我会说明calc。截至本文时,跨浏览器尚不支持calc;但是,您可以查看this link here以查看您的目标浏览器是否受支持。我修改了matt的假设案例,以便在an example on jsFiddle中使用calc。从本质上讲,它是一个纯粹的CSS解决方案,可以完成卡萨布兰卡在答案中提出的建议。例如,如果浏览器支持calc,则height: calc(100% - 200px);和类似属性都有效。

答案 4 :(得分:0)

有时候解决方法可能是:

#rest {
  height: 100%;
  padding-bottom: 200px;
}

div本身会过高,但是由于填充的原因,其内容将具有正确的高度。

答案 5 :(得分:-3)

您可以使用嵌套的div标签执行此操作。你有一个指定左边的宽度,然后另一个留空。要填充另一侧的其余部分,您将在右侧div中嵌入100%相对div。像这样:

<div style="width:100%">
  <div style="width:300px;background-color:#FFFF00;float:left">
  </div>
  <div style="margin-left:300px">
    <div style="position:relative;left:0px;width:100%;background-color:#00FFFF">
    </div>
  </div>
</div>

答案 6 :(得分:-5)

尝试

height: 100%;

height: auto;
相关问题