2017-06-06 158 views
1

我在里面有内容的div。2元素填充剩余高度

我希望顶部和底部的div填补余下的空间。

喜欢的东西this

<div class="container"> 
    <div class="top"> 

    </div> 
    <div class="middle"> 
     Content 
    </div> 
    <div class="bottom"> 

    </div> 
</div> 

如果可能的话我想设定最低高度的顶部和底部的容器。

回答

1

借助Flexbox,就可以做这

html, body { 
 
    margin: 0; 
 
} 
 
body { 
 
    display: flex;   /* IE fix */ 
 
} 
 
.container { 
 
    display: flex; 
 
    flex-direction: column; 
 
    min-height: 100vh; 
 
    width: 100%;    /* IE fix */ 
 
} 
 
.top, .bottom { 
 
    flex: 1;     /* fill remaining space */ 
 
    background: lightblue; 
 
} 
 
.middle { 
 
    background: lightgreen; 
 
}
<div class="container"> 
 
    <div class="top"> 
 

 
    </div> 
 
    <div class="middle"> 
 
     Content 
 
    </div> 
 
    <div class="bottom"> 
 

 
    </div> 
 
</div>


如果你需要,你还可以添加一个min-heighttop/bottom元素

html, body { 
 
    margin: 0; 
 
} 
 
body { 
 
    display: flex;   /* IE fix */ 
 
} 
 
.container { 
 
    display: flex; 
 
    flex-direction: column; 
 
    min-height: 100vh; 
 
    width: 100%;    /* IE fix */ 
 
} 
 
.top, .bottom { 
 
    flex: 1;     /* fill remaining space */ 
 
    background: lightblue; 
 
    min-height: 200px;  /* set a min-height */ 
 
} 
 
.middle { 
 
    background: lightgreen; 
 
}
<div class="container"> 
 
    <div class="top"> 
 

 
    </div> 
 
    <div class="middle"> 
 
     Content 
 
    </div> 
 
    <div class="bottom"> 
 

 
    </div> 
 
</div>

+0

伟大的回应,这似乎正是我需要感谢! – KevinKelbie

+0

@WizardCoder我知道你没有说它是坏的,但再次看看,IE10支持2012年的Flexbox语法,它在上面的代码中是'display:-ms-flexbox;','-ms-flex-direction :列'和'-ms-flex:1;' – LGSon

0

.top{ 
 
min-height:100px; 
 
} 
 
.bottom{ 
 
min-height:100px; 
 
}

,或者你可以使用不同的meseurment - 像VH - 的观点高度等 忘了补充 - 它会进入你的CSS文件

+0

但这不会填充剩余空间。 – KevinKelbie

+0

你想使用jQuery吗?你需要使用动态计算,如果是的话,我可以告诉你简短的jQuery功能,可以帮助你 –

+0

当然,如果这是最简单的方法。谢谢您的帮助! :) – KevinKelbie

0

这里是你较真表的解决方案。

html, body { 
 
    margin: 0; 
 
    height:100%; 
 
} 
 
.container { 
 
    display: table; 
 
    height: 100%; 
 
    width: 100%; 
 
} 
 
.container > div { 
 
    display: table-row; 
 
} 
 
.table-cell { 
 
    display: table-cell; 
 
} 
 
.top, .bottom { 
 
    background: #ADD8E6; 
 
} 
 
.middle { 
 
    background: #90EE90; 
 
    height:1px; 
 
}
<div class="container"> 
 
    <div class="top"> 
 
    <div class="table-cell"> 
 

 
    </div> 
 
    </div> 
 
    <div class="middle"> 
 
    <div class="table-cell"> 
 
     Content 
 
    </div> 
 
    </div> 
 
    <div class="bottom"> 
 
    <div class="table-cell"> 
 

 
    </div> 
 
    </div> 
 
</div>

+0

另一个伟大的解决方案谢谢!这比柔性解决方案更友好吗? – KevinKelbie

+0

不使用flexbox的唯一原因是如果你想支持IE9。同样在具有复杂结构的大型网站上,flexbox可以稍微增加页面加载时间。我个人只有在没有其他方法来实现我想要的布局时才使用flexbox。所有人都说,在这种情况下,我看不到使用flex的任何问题。 – WizardCoder