水平居中
文本水平居中
<div>水平居中文字</div>
div{text_align:center;}
元素水平居中
<div>元素水平居中</div>
div{margin:0 auto;} 设置margin:0 auto 即可让元素水平居中
垂直居中
单行垂直居中
<div>单行垂直居中</div>
div{height:100px;line-height:100px;}
设置line-height 与height的高度相同
多行垂直居中
利用position和负边距,让元素的顶部与居中线对齐,再让元素上移50%的高度
<div class='parent'><div class='child'>垂直居中</div></div>
.parent{position:relative;}
.child{position:absolute;top:50%;margin-top:150px;}
margin-top 为元素自身高度的一半
行内元素垂直对齐
该方法适用于行内元素和单元格元素(table-cell),常用于行内元素内img垂直对齐
<p><img src="img.png">图片相对于文字中间对齐</p>
img{vertical-align:middle;}
水平&&垂直居中
单行文本水平垂直居中
<div>单行文本水平垂直居中</div>
div{height:100px;line-height:100px;text-align:center;}
元素水平垂直居中
<div class='parent'><div class='child'>垂直居中</div></div>
.parent{position:relative;}
.child{position:absolute;left:50%;top:50%;width:100px;height:100px;margin-top:-50px;margin-left:-50px;}
或者
.child{position:absolute;left:50%;margin:-50px auto 0 auto ;width:100px;height:100px}