在平常的工作中,我们经常会遇到这样的需求,就是两端固定,中间自适应的三栏布局,比如移动端头部导航,那么该怎么实现呢,我总结了一下几种方式:
方式一:浮动
样式代码:
<style>
* {
margin: 0;
padding: 0;
}
.box {
height: 100px;
}
.left, .right {
width: 100px;
height: 100%;
background-color: red;
}
.left {
float: left;
}
.right {
float: right;
}
.center {
height: 100%;
background-color: yellow;
}
</style>
布局代码:
<div class="box">
<div class="left"></div>
<div class="right"></div>
<div class="center">
<h2>我是中间自适应布局</h2>
</div>
</div>
注意:center要放到最后
方式二:绝对定位
样式代码:
<style>
* {
margin: 0;
padding: 0;
}
.box {
position: relative;
height: 100px;
}
.box > div {
position: absolute;
}
.left, .right {
width: 100px;
height: 100%;
background-color: red;
}
.left {
left: 0;
}
.right {
right: 0;
}
.center {
position: absolute;
left: 100px;
right: 100px;
height: 100%;
background-color: yellow;
}
</style>
布局代码:
<div class="box">
<div class="left"></div>
<div class="center">
<h2>我是中间自适应布局</h2>
</div>
<div class="right"></div>
</div>
方式三:flex布局
样式代码:
<style>
* {
margin: 0;
padding: 0;
}
.box {
display: flex;
height: 100px;
}
.left, .right {
flex: 0 0 100px;
width: 100px;
height: 100%;
background-color: red;
}
.center {
flex: 1;
height: 100%;
background-color: yellow;
}
</style>
布局代码:
<div class="box">
<div class="left"></div>
<div class="center">
<h2>我是中间自适应布局</h2>
</div>
<div class="right"></div>
</div>
这也是我在移动端最喜欢的布局
方式四:被无情抛弃的table布局
样式代码:
<style>
* {
margin: 0;
padding: 0;
}
.box {
display: table;
width: 100%;
height: 100px;
}
.box > div {
display: table-cell;
}
.left, .right {
width: 100px;
height: 100%;
background-color: red;
}
.center {
background-color: yellow;
}
</style>
布局代码:
<div class="box">
<div class="left"></div>
<div class="center">
<h2>我是中间自适应布局</h2>
</div>
<div class="right"></div>
</div>
方式五:grid网格布局
样式代码:
<style>
* {
margin: 0;
padding: 0;
}
.box {
display: grid;
width: 100%;
/* 每行高100px */
grid-template-rows: 100px;
/**
列的宽度
第一列100
第二列自适应
第三列100
*/
grid-template-columns: 100px auto 100px;
}
.left, .right {
background-color: red;
}
.center {
background-color: yellow;
}
</style>
布局代码:
<div class="box">
<div class="left"></div>
<div class="center">
<h2>我是中间自适应布局</h2>
</div>
<div class="right"></div>
</div>
以上就是我总结的几种方式,希望和大家多多交流,感谢指正!