css元素水平垂直居中的方式

实现方法

1、

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

此代码会使任意子元素相对最近有定位的父元素水平垂直居中。

css元素水平垂直居中的方式
显示效果:
css元素水平垂直居中的方式

2、

position: absolute;
left: 50%;
top: 50%;
margin-top:-xxpx;(xx=height/2)
margin-left: -xxpx;(xx=left/2)

利用绝对定位使元素居中。
这个方法有个缺点:要事先知道定位元素的大小。
css元素水平垂直居中的方式

显示效果:
css元素水平垂直居中的方式