一:使用絕對定位給4個方向都為0;用margin自動,實現box居中
示例代碼:
.box { position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 100px; height: 100px; margin: auto; }二:采用絕對定位,定位時上邊距與左邊距都給50%,在利用margin屬性減去當前盒子的一半寬度與高度,實現居中效果
示例代碼
.box{ position: absolute; top: 50%; left: 50%; width: 100px; height: 100px; margin: -50px 0 0 -50px; }
三:利用transform:translate(-50%, -50%)方法實現居中,此方法適用於不知width、height的情況下
示例代碼:
.box { position: absolute; top: 50%; left: 50%; width: 100px; height: 100px; transform: translate(-50%, -50%); }
視圖效果:

