当浏览器位于固定div之上时,如何设置div全高度的浏览器?

时间:2014-11-06 14:24:08

标签: javascript jquery html css css3

我有3个div。第一个是100%宽度和100px高。第二个是100%宽,但我想让它成为浏览器的高度。第三个是100%宽和100px高,但第三个div固定在屏幕的底部。

这是我的尝试,不会让中间div填充顶部和底部div之间的空间

.top, .bottom{
    background-color: grey;
    width: 100%;
    height: 100px;
}

.bottom{
    position: fixed;
    bottom: 0;
    left: 0;
}

.middle{
    background-color: white;
    width: 100%;
    height: 100%;
    border: 1px solid red;
}

这是我尝试过的{JESFiddle JsFiddle

如何让中间div扩展以填充上下div之间的空间?

5 个答案:

答案 0 :(得分:3)

有很多方法可以做到这一点。

一个简单的(虽然您必须检查浏览器兼容性)是使用calc()。然后你不需要在底部div上使用固定位置:

Updated JsFiddle

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

.top, .bottom{
    background-color: grey;
    width: 100%;
    height: 100px;
}

.middle{
    background-color: white;
    width: 100%;
    height: calc(100% - 200px);
    outline: 1px solid red;
}

答案 1 :(得分:1)

如果这确实是你唯一的要求,那么你可以放弃

.middle {
    height: calc(100vh - 200px);
}

但如果你想更进一步,那么看看flexbox可能是明智之举。此页面包含一些不错的信息http://css-tricks.com/snippets/css/a-guide-to-flexbox/

答案 2 :(得分:1)

首先,您需要通过将htmlbody设置为100%高度来修正整个页面的高度。 然后,您需要为.middle div添加一个底部边距,以考虑底部的高度:

html, body {
    height: 100%;
}

.top, .bottom {
    background-color: grey;
    width: 100%;
    height: 100px;
}

.bottom {
    position: fixed;
    bottom: 0;
    left: 0;
}

.middle {
    background-color: white;
    width: 100%;
    height: 100%;
    border: 1px solid red;
    margin-bottom: 100px;
}
<div class="top"></div>
<div class="middle">some text</div>
<div class="bottom"></div>

答案 3 :(得分:1)

尝试使用view-port height。

height: 100vh;

如果不这样,我会考虑使用flex:https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes

它的目的是做你想做的事。

答案 4 :(得分:0)

如果你可以使用flex和vh,这将有效。

body {
    display: flex;
    flex-direction:column;
}
.top, .bottom{
    background-color: grey;
    flex: 1 1 100px;
}
.middle{
    background-color: white;
    border: 1px solid red;
    flex: 1 1 100vh;
}