(1) width: (xxx)px; margin: 0 auto;
css
使用场景:页面总体水平居中,有具体宽度要求。html
<div class="wrap"> <div class="content"></div> </div>
.content { width:1000px; height:100px; background:red; margin:0 auto; }
(2) text-align: center; display: inline-block;
css3
使用场景:子元素有多个且须要水平居中排列浏览器
<div class="wrap"> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> </div>
.wrap { text-align: center; } .content { display: inline-block; width: 100px; height: 100px; background: red; }
(3) absolute
+left:50%
+margin-left:-width/2
布局
使用场景:子元素宽度肯定,子元素之间互不影响flex
<div class="wrap"> <div class="content"> 快过年了快过年了快过年了快过年了快过年了快过年了快过年了 </div> </div>
.wrap { position: relative; } .content { position: absolute; left: 50%; width: 200px; height: 100px; margin-left: -100px; background: red; }
(4) absolute
+left:50%
+translateX(-50%)
spa
使用场景:子元素宽度不肯定,支持css3的translate
属性,子元素之间互不影响code
<div class="wrap"> <div class="content"> 快过年了快过年了快过年了快过年了快过年了快过年了快过年了 </div> </div>
.wrap { position: relative; } .content { position: absolute; left: 50%; height: 100px; background: red; transform: translateX(-50%); }
(5) flex
布局orm
使用场景: 支持flex
布局方式的浏览器均可以使用此布局,结合了(2)(4)两种方法的优势,无需考虑子元素宽度,且支持多个子元素居中htm
<div class="wrap"> <div class="content"> 快过年了快过年了快过年了快过年了快过年了快过年了快过年了 </div> </div>
.wrap { display: flex; justify-content: center; } .content { height: 100px; background: red; }
相比水平居中布局,垂直居中稍微坑了一点,实现方法并无灵活。
(1)table-cell
布局
使用场景:多行文字上下居中
<div class="wrap"> <div class="content"> 快过年了快过年了快过年了快过年了快过年了快过年了快过年了 </div> </div>
.wrap { display: table-cell; vertical-align: middle; height: 200px; } .content { width: 100px; background: red; }
(2)absolute
+top:50%
+margin-top:-height/2
使用场景:与水平居中同样,适用于子元素高度肯定,不会对其余子元素形成影响的状况下的上下居中,因为是绝对定位,父元素须要占据空间,若没有其余子元素,需设置一个高度
.wrap { position: relative; height: 200px; } .content { position: absolute; top: 50%; width: 300px; height: 100px; margin-top: -50px; background: red; }
(3) absolute
+top:50%
+translateY(-50%)
使用场景:与水平居中同样,适用于子元素高度不肯定,不会对其余子元素形成影响的状况下的上下居中,因为是绝对定位,父元素须要占据空间,若没有其余子元素,需设置一个高度
.wrap { position: relative; height: 200px; } .content { position: absolute; top:50%; background: red; transform: translateY(-50%); }
(4) flex
布局
使用场景: 支持flex
布局方式的浏览器均可以使用此布局,无需考虑子元素高度,书写简便快捷
<div class="wrap"> <div class="content"> 快过年了快过年了快过年了快过年了快过年了快过年了快过年了 </div> </div>
.wrap { display: flex; align-items: center; height: 200px; } .content { background: red; }