在其上方具有可变高度内容而不使用绝对定位的页脚?

时间:2014-08-21 22:05:54

标签: html css

我已经得到以下内容(http://jsfiddle.net/u2zedzob/1/

<div class="wrapper">
    <div class="main-content"></div>
    <div class="footer"></div>
</div>

*, *:before, *:after {
    box-sizing: border-box;
 }

.wrapper {
    background-color: red;
    height: 300px;
    width: 300px;
}

.main-content {
    height: 100%;
    width: 100%;
    background-color: green;
}

.footer {
    height: 30px;
    width: 100%;
    background-color: blue;
}

在此示例中,.footer位于.main-content下方,但突破.wrapper。我希望.main-content在确定它的高度时尊重.footer的高度。

我不需要支持旧浏览器。只是最新的Chrome / FF。

我可以想到几种方法来实现这一目标。

  • position:absolute,.footer {bottom:0},。main-content {bottom:30}
  • .main-content {height:calc(100% - 30px)}
  • 可能显示:table / display:table-cell还有其他一些烦恼?

我不喜欢这个位置:绝对解决方案,因为这意味着如果我更改.footer的高度,我必须知道更新.main-content的底值。使用calc也是如此。我可以在我的CSS预处理器中存储一个变量来帮助解决这个问题,但它仍然感觉不对。

我之前在表格单元格布局方面取得了成功,但是在水平方向上类似的情况下,但我似乎无法让CSS在垂直方面运行良好。

我想知道其他人会在这种情况下使用什么方法。感谢

1 个答案:

答案 0 :(得分:0)

解决方案是使用flexboxes:http://jsfiddle.net/u2zedzob/10/

*, *:before, *:after {
    box-sizing: border-box;
 }

.wrapper {
    background-color: red;
    height: 300px;
    width: 300px;
    display: flex;
    flex-direction: column;
}

.main-content {
    height: 100%;
    width: 100%;
    background-color: green;
}

.footer {
    min-height: 30px;
    width: 100%;
    background-color: blue;
}