两种方式实现盒子水平垂直居中

一:在知道宽高的情况下:

<div style="

200px;

height:200px;

background: red;

position: absolute;

top: 0;

bottom: 0;

left: 0;

right: 0;

margin: auto;

"></div>

二:在不知道宽高的情况下:padding会把盒子撑开,相当于宽高了。

<div style="

padding: 30px;

background: pink;

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%,-50%);

"></div>

另外:可以加几个兼容:

-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
原文地址:https://www.cnblogs.com/lvqiupingboke-2019/p/12055720.html