div在body中水平垂直居中的方法

这个方法的前提是要已知div的宽和高。

height: 480px;
width: 720px;
position: absolute;

首先设置好div的宽和高,并设置position属性为absolute.

left: 50%;
top: 50%;

然后将div距离body窗口的左边框和上边框的距离设置为50%.

margin: -240px 0 0 -360px;

最后把这个div分别左移上移,上移距离为宽高的一半.

效果图:

hfc830cb967d6457a86683c4447bb6d98e-5342322

    .father {
      height: 480px;
      width: 720px;
      position: absolute;
      left: 50%;
      top: 50%;
      margin: -240px 0 0 -360px;
      background-color: red;
    }