CSS实现水平垂直居中

1、相对于窗口

实现一:

.center{50px;height:20px;background:#fff;position:absolute;top:50%;left:50%;margin-top:-10px;margin-left:-25px;}

父容器要用相对定位position:relative;否则的话子元素会相对于浏览器窗口进行绝对定位。

子容器绝对定位,top:50%;left:50%;margin-top,margin-left的值取该容器高度,宽度的一半的负值。

实现二:

.center{50px;height:20px;background:#fff;position:absolute;top:50%;left:50%;transform: translate(-50%,50%);}

变动,位移;如下表示向右位移120像素,如果向上位移,把后面的“0”改个值就行,向左向下位移则为负“-”。

原文地址:https://www.cnblogs.com/BurtBlog/p/6409246.html