三栏布局是开发中常用的布局方式,这里总结了三栏布局(水平方向)的五种方案
题目:假设高度已知,其中左栏,右栏宽度各为300px,中间自适应。
微信图片_20181126195618.png
方案1:浮动解决方案
原理:设置左边元素为左浮动,右边元素为有浮动,左边/右边元素宽度都为300px,中间元素会自动占据剩余空间。
- html部分
<section class="layout">
<div class="left"></div>
<div class="right"></div>
<div class="center">
<h1>浮动解决方案</h1>
1.这是三栏布局中间部分
2.这是三栏布局中间部分
</div>
</section>
- css部分
.layout div{
min-height: 100px;
}
.left{
float: left;
width: 300px;
background-color: red;
}
.right{
float: right;
width: 300px;
background-color: blue;
}
.center{
background-color: yellow;
}
-
显示结果
微信图片_20181126150524.png
方案2:绝对定位解决方案
原理:设置所有子元素为绝对定位,左边/右边元素宽度都为300px,中间元素通过left:300px,right:300px定位到中间,而且宽度会自动占据剩余空间。
- html部分
<section class="layout">
<div class="left"></div>
<div class="right"></div>
<div class="center">
<h1>绝对定位解决方案</h1>
1.这是三栏布局中间部分
2.这是三栏布局中间部分
</div>
</section>
- css部分
.layout div{
min-height: 100px;
position: absolute;
}
.left{
position: absolute;
left: 0;
width: 300px;
background-color: red;
}
.right{
position: absolute;
right: 0;
width: 300px;
background-color: blue
}
.center{
left: 300px;
right: 300px;
background-color: yellow;
}
-
显示结果
微信图片_20181126150528.png
方案3:flexbox解决方案
原理:设置容器为flexbox,左边/右边元素宽度都为300px,中间元素通过flex:1属性占据剩余空间。
- html部分
<section class="layout">
<div class="left"></div>
<div class="center">
<h1>flexbox解决方案</h1>
1.这是三栏布局中间部分
2.这是三栏布局中间部分
</div>
<div class="right"></div>
</section>
- css部分
.layout div{
min-height: 100px;
}
.layout{
display: flex;
}
.left{
width: 300px;
background-color: red;
}
.right{
width: 300px;
background-color: blue
}
.center{
flex: 1;
background-color: yellow;
}
-
显示结果
微信图片_20181126150531.png
方案4:表格布局解决方案
原理:设置容器为表格,宽度为100%,与页面宽度相同。左边/右边元素宽度都为300px,剩余的宽度会自动分配给中间元素
- html部分
<section class="layout">
<div class="left"></div>
<div class="center">
<h1>表格布局解决方案</h1>
1.这是三栏布局中间部分
2.这是三栏布局中间部分
</div>
<div class="right"></div>
</section>
- css部分
.layout div{
display: table-cell;
}
.layout{
width: 100%;
height: 100px;
display: table;
}
.left{
width: 300px;
background-color: red;
}
.right{
width: 300px;
background-color: blue
}
.center{
background-color: yellow;
}
-
显示结果
微信图片_20181126150535.png
方案5:网格布局解决方案
原理:设置容器为网格,宽度为100%,与页面宽度相同。左边/右边两列的宽度都为300px,剩余的空间会自动分配给中间列。
- html部分
<section class="layout">
<div class="left"></div>
<div class="center">
<h1>网格布局解决方案</h1>
1.这是三栏布局中间部分
2.这是三栏布局中间部分
</div>
<div class="right"></div>
</section>
- css部分
.layout{
width: 100%;
display: grid;
grid-template-rows: 100px;
grid-template-columns: 300px auto 300px;
}
.left{
background-color: red;
}
.right{
background-color: blue
}
.center{
background-color: yellow;
}
-
显示结果
微信图片_20181126150538.png
网友评论