三栏式布局
三栏式布局就是两边固定,中间自适应。
三栏式布局实现方法有很多,包括:
- 流体布局
- BFC三栏布局
- 双飞翼布局
- 圣杯布局
- Flex布局
- Table布局
- 绝对定位布局
- 网格布局
流体布局
左侧向左浮动、右侧向右浮动,最后渲染中间实现;最后渲染中间也就意味着在html中内容div写在最后,并设置中间模块的 margin 值使中间模块宽度自适应
缺点就是主要内容无法最先加载,当页面内容较多时会影响用户体验
<div class="wrap">
<div class="left">左侧</div>
<div class="right">右侧</div>
<div class="main">中间</div>
</div>
<style>
*{
margin: 0;
border: 0;
}
.left{
width: 100px;
height:500px;
background-color: yellow;
float: left;
}
.right{
width: 200px;
height: 500px;
background-color: palevioletred;
float: right;
}
.main{
height: 500px;
background-color: aqua;
margin-left: -100px;
margin-right: -200px;
}
</style>
效果:
BFC布局
BFC 区域,不会与浮动元素重叠。左右模块各自向左右浮动,并设置中间模块的
overflow:hidden
,使中间模块宽度自适应
<style>
*{
margin: 0;
border: 0;
}
.left{
width: 100px;
height:500px;
background-color: yellow;
float: left;
}
.main{
height: 500px;
background-color: aqua;
overflow: hidden;
}
.right{
width: 200px;
height: 500px;
background-color: palevioletred;
float: right;
}
</style>
双飞翼布局
按照“中左右”的顺序排放元素,都设置浮动,最中间元素宽度设置为100%,
利用左右margin负边距将左右元素拉到左右位置
利用的是浮动元素和 margin 负值(中间设置子元素,margin的左右值是左右两边元素的宽度),主体内容可以优先加载,HTML 代码结构稍微复杂点。
<div class="wrap">
<div class="center">
<div class="center-child">中间mmmmmmmmmm</div>
</div>
<div class="left">左侧</div>
<div class="right">右侧</div>
</div>
<style>
.wrap{
border: 1px solid #000;
overflow: hidden;
}
.center{
width:100%;
height:500px;
background-color: yellow;
float: left;
}
.center-child{
width:100%;
height: 400px;
background-color: aqua;
//为子元素设置左右margin,防止内容被遮挡
margin-left: 150px;
margin-right: 250px;
}
.left{
width:150px;
height:500px;
background-color: red;
float: left;
margin-left: -100%;
}
.right{
width:250px;
height:500px;
background-color: blue;
float: left;
margin-left:-250px;
}
</style>
效果:
圣杯布局
按照“中左右”的顺序排放元素,都设置浮动,最中间元素宽度设置为100%,
利用左右margin负边距将左右元素拉到左右位置
圣杯布局使用padding和定位(父元素设置左右padding,再给左右元素设置相对定位)
<div class="wrap">
<div class="center"></div>
<div class="left"></div>
<div class="right"></div>
</div>
<style>
.wrap{
border:1px red solid;
padding:0 250px 0 200px;
}
.wrap>div{
float: left;
height:300px;
}
.wrap:after{
display:block;
content: "";
clear:both;
}
.center{
width:100%;
background-color:yellow;
}
.left{
width:200px;
background-color:blue;
margin-left:-100%;
position:relative;
left:-200px;
}
.right{
width:250px;
background-color:green;
margin-left:-250px;
position:relative;
right:-250px;
}
</style>
效果:
Flex布局
给父元素设置display: flex;justify-content: space-around
即可,代码简单方便
<div class="wrap">
<div class="left">左侧</div>
<div class="center">中间</div>
<div class="right">右侧</div>
</div>
<style>
.wrap{
display: flex;
justify-content: space-around;
}
.left{
width:200px;
height:500px;
background-color: blue;
}
.center{
width:100%;
height:500px;
background-color: yellow;
}
.right{
width:100px;
height:500px;
background-color: pink;
}
</style>
效果:
最后,要注意区分圣杯布局和双飞翼布局哦1