css的div动态水平垂直居中

 

div动态水平垂直居中,思路如下:

(1)先定位。如果相对于距离最近的父元素,用absolute;如果相对于body,用fixed。

(2)然后,top和left都设为50%。

(3)要居中的div的margin-top和margin-left,都设置为该div高度和宽度的一半。

position:absolute;

200px;

height:100px;

left:50%;

top:50%;

border:1px solid red;

margin-left:-100px;

margin-top:-50px;

如果只是水平居中,只用一个margin就行了。

margin:0 auto;