居中元素宽高已知
1. absolute+margin auto
.child{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top:0;
left:0;
bottom: 0;
right: 0;
margin: auto;
}
2. absolute+负margin
.child{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top:50%;
left:50%;
margin-top: -50px;
margin-left:-50px;
}
3. absolute+calc
.child{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top:cacl(50% - 50px);
left:cacl(50% - 50px);
}
居中元素宽高未知
1. absolute+transform
.parent1{
position: relative;
width: 200px;
height: 200px;
border: 2px solid lightblue;
}
.child1{
position: absolute;
background-color: pink;
top:50%;
left: 50%;
transform: translate(-50%,-50%);
}
2. line-height + vertica-align
.parent1{
width: 200px;
height: 200px;
border: 2px solid lightblue;
line-height:200px;
text-align:center;
}
.child1{
background-color: pink;
vertical-align:middle;
line-height:initial;
}
3. table表格元素
<table>
<tbody>
<tr>
<td class='parent2'>
<div class='child2'>我是表格元素垂直居中对齐</div>
</td>
</tr>
</tbody>
</table>
.parent2{
width: 200px;
height: 200px;
border: 2px solid lightblue;
text-align:center;
}
.child2{
display:inline-block;
}
4. css-table表格样式
.parent1{
width: 200px;
height: 200px;
border: 2px solid lightblue;
display:table-cell;
text-align:center;
vertical-align:middle;
}
.child1{
background-color: pink;
display:inline-block;
}
5. flex布局
.parent1{
width: 200px;
height: 200px;
border: 2px solid lightblue;
display:flex;
justify-content:center;
align-items:center;
}
.child1{
background-color: pink;
6. flex+margin auto
.parent1{
width: 200px;
height: 200px;
border: 2px solid lightblue;
display:flex;
}
.child1{
background-color: pink;
margin:auto;
7. grid网络布局1
.parent1{
width: 200px;
height: 200px;
border: 2px solid lightblue;
display:grid;
justify-content:center;
align-items:center;
}
.child1{
background-color: pink;
8. grid网格布局2
.parent1{
width: 200px;
height: 200px;
border: 2px solid lightblue;
display:grid;
}
.child1{
background-color: pink;
justify-self:center;
align-self:center;