技术背景
在前端开发中,经常会遇到需要让某个div元素填充屏幕剩余高度的需求,比如创建具有固定头部和底部,中间内容区域自适应填充剩余空间的布局。随着CSS技术的发展,有多种方法可以实现这一需求。
实现步骤
Flexbox方法
- 所有主流浏览器和IE11+都支持Flexbox,对于IE 10或更旧版本,可以使用FlexieJS垫片。
- 示例代码如下:
html,
body {
height: 100%;
margin: 0;
}
.box {
display: flex;
flex-flow: column;
height: 100%;
}
.box .row {
border: 1px dotted grey;
}
.box .row.header {
flex: 0 1 auto;
}
.box .row.content {
flex: 1 1 auto;
}
.box .row.footer {
flex: 0 1 40px;
}
<div class="box">
<div class="row header">
<p><b>header</b>
<br />
<br />(sized to content)</p>
</div>
<div class="row content">
<p>
<b>content</b>
(fills remaining space)
</p>
</div>
<div class="row footer">
<p><b>footer</b> (fixed height)</p>
</div>
</div>
CSS Table方法
- 可以使用CSS表格来实现布局。
- 示例代码如下:
body
{
display:table;
width:100%;
}
div
{
display:table-row;
}
div + div
{
height:100%;
}
<body>
<div>hello </div>
<div>there</div>
</body>
calc()方法
- 当知道头部和底部元素的固定高度时,可以使用CSS3的calc()函数。
- 示例代码如下:
html,
body {
height: 100%;
}
header {
height: 100px;
background: grey;
}
section {
height: calc(100% - (100px + 150px));
background: tomato;
}
footer {
height: 150px;
background-color: blue;
}
<header>100px</header>
<section>Expand me for remaining space</section>
<footer>150px</footer>
vh单位方法
- vh代表视口高度,可以直接使用该单位设置元素高度。
- 示例代码如下:
body {
padding: 0;
margin: 0;
}
.full-height {
width: 100px;
height: 100vh;
background: red;
}
<div class="full-height">
</div>
CSS Grid方法
- 使用CSS Grid布局可以很方便地实现布局。
- 示例代码如下:
* {
margin: 0;
padding: 0;
}
html {
height: 100%;
}
body {
min-height: 100%;
display: grid;
grid-template-rows: auto 1fr auto;
}
header {
padding: 1em;
background: pink;
}
main {
padding: 1em;
background: lightblue;
}
footer {
padding: 2em;
background: lightgreen;
}
<header>HEADER</header>
<main>MAIN</main>
<footer>FOOTER</footer>
最佳实践
- xxxxxxxxxx display: -webkit-box;display: -webkit-flex;display: -moz-box;display: -ms-flexbox;display: flex;-webkit-flex-align: center;-ms-flex-align: center;-webkit-align-items: center;align-items: center;css
- 如果需要支持旧版本浏览器,可以结合使用CSS Table或JavaScript来实现。
- 在使用calc()函数时,确保父元素的高度已经正确设置。
常见问题
- 兼容性问题:不同浏览器对CSS属性的支持可能不同,需要进行充分的测试。
- 滚动问题:当内容区域超出屏幕高度时,可能会出现滚动条的问题,需要进行适当的处理。
- 布局错乱:在响应式设计中,布局可能会因为屏幕尺寸的变化而错乱,需要使用媒体查询进行调整。