本文列举了水平和垂直居中的方法,分别在已知宽高和未知宽高的情况。
从以下方法不难看出,要制造居中,大体分为位移居中和直接设置居中。
html
<div class="farther">
<div class="son"></div>
</div>
4个方法
已知宽高:
1.定位+margin
.father {
width: 500px;
height: 500px;
background: #ccc;
position: relative;
}
.son {
width: 200px;
height: 200px;
background: orange;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
}
2..定位+calc
.father {
width: 500px;
height: 500px;
background: #ccc;
position: relative;
}
.son {
width: 200px;
height: 200px;
background: orange;
position: absolute;
top:( 50%-100px);
left: calc(50%-100px);
}
3.定位+制造位移
.father {
width: 500px;
height: 500px;
background: #ccc;
position: relative;
}
.son {
width: 200px;
height: 200px;
background: orange;
position: absolute;
transform: translate(-50%,-50%)
}
*****忘了******
4.diplay:flex
.father {
width: 500px;
height: 500px;
background: #ccc;
display:flex;
justify-content: center;
align-items: center;
}
.son {
width: 200px;
height: 200px;
background: orange;
}