总结完水平方向的三栏布局之后,再来总结下垂直方向的三栏布局,这在移动端的开发中非常常见。
要求:假设宽度已知,其中上栏,下栏高度各为100px,中间高度自适应。
总结:在正常情况下,以下四种方案都能达到要要求。但是当中间栏的内容较多时,方案3的表格布局解决方案会占据上栏和下栏的空间,所以不建议采用。
方案1:绝对定位解决方案
- html部分
<section class="layout">
<div class="top"></div>
<div class="center">
<h1>绝对定位解决方案</h1>
<p>这是三栏布局中间部分</p>
<p>这是三栏布局中间部分</p>
</div>
<div class="bottom"></div>
</section>
- css部分
.layout div{
min-height: 100px;
width: 100%;
position: absolute;
}
.layout{
height: 100vh;
position: relative;
}
.top{
top: 0;
background-color: red;
}
.bottom{
bottom: 0;
background-color: blue;
}
.center{
top: 100px;
bottom: 100px;
overflow: auto;
background-color: yellow;
}
方案2:flexbox解决方案
- html部分
<section class="layout">
<div class="top"></div>
<div class="center">
<h1>flexbox解决方案</h1>
<p>这是三栏布局中间部分</p>
<p>这是三栏布局中间部分</p>
</div>
<div class="bottom"></div>
</section>
- css部分
.layout div{
min-height: 100px;
}
.layout{
height: 100vh;
display: flex;
flex-direction: column;
}
.top{
background-color: red;
}
.bottom{
background-color: blue;
}
.center{
flex: 1;
background-color: yellow;
overflow: auto;
}
方案3:表格布局解决方案
- html部分
<section class="layout">
<div class="top row">
<div class="top-cell cell"></div>
</div>
<div class="center row">
<div class="center-cell cell">
<h1>表格解决方案</h1>
<p>这是三栏布局中间部分</p>
<p>这是三栏布局中间部分</p>
</div>
</div>
<div class="bottom row">
<div class="bottom-cell cell"></div>
</div>
</section>
- css部分
.layout .row{
display: table-row;
min-height: 100px;
}
.layout .cell{
display: table-cell;
}
.layout{
height: 100vh;
width: 100%;
display: table;
}
.top{
background-color: red;
}
.bottom{
background-color: blue;
}
.center{
overflow: auto;
background-color: yellow;
}
方案4:网格布局解决方案
- html部分
<section class="layout">
<div class="top"></div>
<div class="center">
<h1>网格解决方案</h1>
<p>这是三栏布局中间部分</p>
<p>这是三栏布局中间部分</p>
</div>
<div class="bottom"></div>
</section>
- css部分
.layout{
height: 100vh;
display: grid;
grid-template-rows: 100px auto 100px;
grid-template-columns: 100%;
}
.top{
background-color: red;
}
.bottom{
background-color: blue;
}
.center{
overflow: auto;
background-color: yellow;
}