1.绝对定位法
2.使用浮动
3.圣杯布局
4.flex布局
1.绝对定位法
<style type="text/css">
html,body{ margin: 0px;width: 100%; }
#left,#right {
width: 200px;
height: 200px;
background-color: #ffe6b8;
position: absolute;
}
#left {
left:0px;
}
#right {
right: 0px;
}
#center {
margin:0 210px ;
background-color: #eee;
height: 200px;
}
</style>
<body>
<div id = "left">我是左边</div>
<div id = "right">我是右边</div>
<div id = "center">我是中间</div>
</body>
- 原理:通过给左、右盒子绝对定位,然后让居中的盒子用margin值撑开。
- 优点:三个盒子的顺序可以任意
- 缺点:当页面宽度小于等于(左+右盒子宽度),绝对定位的层级更高会把中间盒子遮住。
2.使用浮动
<style type="text/css">
html,body{ margin: 0px;width: 100%; }
#left,#right {
width: 200px;
height: 200px;
background-color: #ffe6b8;
}
#left {
float: left;
}
#right {
float: right;
}
#center {
margin:0 210px ;
background-color: #eee;
height: 200px;
}
</style>
<body>
<div id = "left">我是左边</div>
<div id = "right">我是右边</div>
<div id = "center">我是中间</div>
</body>
3.圣杯布局
<style type="text/css">
.content{padding: 0 100px;}
.col{
float: left;
height: 200px;
position: relative;
}
.left,.right{
width: 100px;
}
.left{
background-color: blue;
margin-left: -100%;
right: 100px;
}
.right{
background-color: green;
margin-left: -100px;
left:100px;
}
.center{
width: 100%;
background-color: pink;
}
</style>
<body>
<div class="content">
<div class="center col">
</div>
<div class="left col">
</div>
<div class="right col">
</div>
</div>
</body>
- content需要给左右内边距等于左右盒子的宽度
- 左中右三个盒子都要设置浮动和相对定位
- 左盒子:margin-left:-100%;right:自身宽度
- 右盒子:margin-left: -自身宽度;left:自身宽度;
4.flex布局
<style type="text/css">
.content {
width: 100%;
display: flex;
}
.left, .right {
width: 200px;
height: 100px;
background: red;
}
.center {
height: 100px;
flex: 1;
background: pink;
}
</style>
<body>
<div class="content">
<div class="left">左</div>
<div class="center">中</div>
<div class="right">右</div>
</div>
</body>
- 父盒子display:flex
- 左右盒子给宽高
- 中盒子flex: 1