Css 居中

若果position为relative,元素没有脱离文档流,则可以用

.center {

  position:relative;

  margin: auto;

}

来达到水平居中。

但是要达到垂直居中,这样是不行的,因为在没有脱离文档流的情况下,margin-top: auto;和margin-bottom: auto;实际都是0

所以可以参考以下方式

.center { 

   900px;
  height: 900px;

  position: absolute;
  margin: auto;
  left: 0; top: 0; right: 0; bottom: 0;

}

默认情况下,块级元素的width默认是100%,所以会填充父元素,要看到有居中的效果,那么就要让元素不充满整个父元素,写上margin:0 auto;让其自动计算两边的margin距离。

参考:Absolute Horizontal And Vertical Centering In CSS

原文地址:https://www.cnblogs.com/IamTing/p/5932447.html