一、水平或垂直居中
1. 单行内容垂直居中
/*height = line-height*/ .center{ height: 4em; line-height: 4em; overflow: hidden; /*保护布局,非必须*/ }
支持:所有块级、内联元素、所有浏览器
缺点:只能显示一行
2. div水平居中
<!--html代码--> <div class="center">div居中了</div>
body{ text-align:center} .center{ margin:0 auto; /*main*/ width:400px; height:100px; border:1px solid #F00 }
3. float
给父元素设置float,然后父元素设置position:relative和left:50%,子元素设置position:relative和left:-50%来实现
二、水平+垂直居中
1. 非固定高度居中
.middle{ position:absolute; top:10px; bottom:10px; }
支持:所有块级、内联元素、所有浏览器
缺点:容器不能固定高度
2. 利用表格
.middle{ display: table-cell; height: 300px; vertical-align: middle; }
缺点:IE无效
3. margin负值
.middle { width: 400px; height: 200px; position: absolute; top: 50%; left: 50%; margin-left: -200px; /* width/2 */ margin-top: -100px; /* height/2 */ }
支持:ie各个版本
缺点:非响应式,宽高固定,需要为padding预留空间或用box-sizing:border-box
4. 完全居中
<!DOCTYPE html> <html> <head> <title>text-align</title> <style type="text/css" media="screen"> body { text-align: center } .middle { background: red; bottom: 0; height: 100px; left: 0; margin: auto; position: absolute; top: 0; right: 0; width: 100px; } </style> </head> <body> <div class="middle">center</div> </body> </html>