1. 水平居中布局
<div class="parent">
<div class="center"></div>
</div>
1.margin+定宽
.center{
width: 100px;
margin: 0 auto;
}
2.table+margin
.center{
display: table;
margin: 0 auto;
}
3.text-align+inline-block
.parent{
text-align: center;
}
.center{
display: inline-block;
}
4.absolute+margin-left
.parent{
position: relative;
}
.center{
position: absolute;
left: 50%;
width: 100px;
margin-left: -50px;
}
5.absolute+transform
.parent{
position: relative;
}
.center{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
6.flex+justify-content
.parent{
display: flex;
justify-content: center;
}
2.垂直居中布局
<div class="parent">
<div class="center"></div>
</div>
1.table-cell+vertical-align
.parent{
display: table-cell;
vertical-align: middle;
}
2.absolute+transform
.parent{
position: relative;
}
.center{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
3.flex+align-items
.parent{
display: flex;
align-items: center;
}
3.水平垂直居中
<div class="parent">
<div class="center"></div>
</div>
1.inline-block+text-align+table-cell+vertical-align
.parent{
display: table-cell;
text-align: center;
vertical-align: middle;
}
.center{
display: inline-block;
}
2.absolute+transfrom
.parent{
position: relative;
}
.center{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
3.flex+justify-content+align-items
.parent{
display: flex;
justify-content: center;
align-items: center;
}
4.一列定宽,一列自适应
<div class="parent">
<div class="left"></div>
<div class="right"></div>
</div>
1.float+margin
.left{
float: left;
width: 100px;
}
.right{
margin-left: 100px;
}
2.float+overflow
.left{
float: left;
width: 100px;
}
.right{
overflow: hidden;
}
3.table
.parent{
distable: table;
width: 100%;
table-layout: fixed; /*列宽由表格宽度和列宽度设定*/
}
.left{
display: table-cell;
width: 100px;
}
.right{
display: table-cell; /*宽度为剩余宽度*/
}
4.flex
.parent{
display: flex;
}
.left{
width: 100px;
}
.right{
flex: 1; /*等价于flex:1 1 0*/
}
5. 三列布局,左右固定宽度,中间自适应
<div class="parent">
<div class="child"></div>
<div class="center"></div>
<div class="right"></div>
</div>
1.float
.left{
float: left;
width: 100px;
}
.right{
float: right;
width: 100px;
}
2.absolute
.parent{
position: relative;
}
.left{
position: absolute;
left: 0;
width: 100px;
}
.center{
position: absolute;
left: 300px;
right: 300px;
}
.right{
position: absolute;
right: 0;
width: 100px;
}
3.table
.parent{
diaplay: table;
width: 100%;
}
.left{
display: table-cell;
width: 100px;
}
.right{
display: table-cell;
width: 100px;
}
4.flex
.parent{
display: flex;
}
.left{
width: 100px;
}
.center{
flex: 1;
}
.right{
width: 100px;
}
5.grid
.parent{
display: grid;
grid-template-columns: 300px auto 300px;
}
6. 三列布局,左中固定宽度,右边自适应
<div class="parent">
<div class="child"></div>
<div class="center"></div>
<div class="right"></div>
</div>
1.float+overflow
.left,
.center{
float: left;
width: 100px;
margin-right: 20px;
}
.right{
overflow: hidden;
}