一.float+margin
左盒子: 左浮动
右盒子: 右浮动
中间盒子: 左右加margin
注意: 盒子的书写顺序是左右中 !!
<div class="container">
<!-- 注意盒子的书写顺序 -->
<div class="left w"></div>
<div class="right w"></div>
<div class="main"></div>
</div>
.w {
width: 200px;
height: 200px;
}
.left {
float: left;
background-color: red;
}
.right {
float: right;
background-color: blue;
}
.main {
margin-left: 200px;
margin-right: 200px;
height: 200px;
background-color: green;
}
二.float+BFC
左盒子: 左浮动
右盒子: 右浮动
中间盒子: 设置overflow:hidden , 来触发BFC
BFC: 块级格式化上下文, 指的就是一个独立渲染的块级区域, 它有自己的一套规则来渲染元素
.w {
width: 200px;
height: 200px;
}
.left {
float: left;
background-color: red;
}
.right {
float: right;
background-color: blue;
}
.main {
overflow: hidden;
height: 200px;
background-color: green;
}
三.Flex弹性盒子布局
container容器: display: flex
中间盒子: flex :1
原理:因为给左右盒子设置了固定的宽度, 子盒子flex为1, 会占满剩下的空间
注意: 盒子的书写顺序是左中右 !!
<div class="container">
<!-- 注意盒子的书写顺序 -->
<div class="left w"></div>
<div class="main"></div>
<div class="right w"></div>
</div>
.w {
width: 200px;
height: 200px;
}
.container {
display: flex;
}
.left {
background-color: red;
}
.right {
background-color: blue;
}
.main {
flex: 1;
height: 200px;
background-color: green;
}
四.table盒子布局
container容器: display: table , width : 100%
左右中盒子: display: table-cell
原理:因为给左右盒子设置了固定的宽度, 中间盒子会占满父盒子剩下的空间
.w {
width: 200px;
height: 200px;
}
.container {
display: table;
width: 100%;
}
.left {
display: table-cell;
background-color: red;
}
.right {
display: table-cell;
background-color: blue;
}
.main {
display: table-cell;
height: 200px;
background-color: green;
}
五.使用定位
container容器: position : relative (子绝父相)
左右盒子: 使用绝对定位, 分别定到左边和右边
中间盒子: 设置左右margin (和第一种浮动的做法有些像)
注意: 盒子的书写顺序是左右中 !!
<div class="container">
<!-- 注意盒子的书写顺序 -->
<div class="left w"></div>
<div class="right w"></div>
<div class="main"></div>
</div>
.w {
width: 200px;
height: 200px;
}
.container {
position: relative;
}
.left {
position: absolute;
left: 0;
background-color: red;
}
.right {
position: absolute;
right: 0;
background-color: blue;
}
.main {
margin: 0 200px;
height: 200px;
background-color: green;
}