常见的水平与垂直居中方法【持续更新】
水平居中
方法一:inline-block + text-align
优点:对IE6-9的兼容性好
缺点:text-align具有继承性,会导致子元素文本也变成居中
1 .parent { 2 height: 200px; 3 width: 100%; 4 background-color: gray; 5 text-align: center; 6 } 7 .child { 8 display: inline-block; 9 height: 100px; 10 width: 100px; 11 background-color: red; 12 }
方法二:table/block + margin
优点:只需要对子元素进行设置就可以实现
缺点:如果子元素脱离文档流(浮动或 固定、绝对定位时),margin属性就会无效
.parent { height: 200px; width: 100%; background-color: gray; } .child { margin: 0 auto; height: 100px; width: 100px; background-color: red; }
方法三:absolute + transform
优点:父级元素是否脱离文档流,不影响子元素水平居中效果
缺点:transform是css3的新增属性,浏览器兼容性不好
PS: 为什么使用transform而不是margin-left,因为margin-left必须知道自身的宽高,而translate可以在不知道宽高的情况下进行居中,tranlate()函数中的百分比是相对于自身宽高的百分比,所以能进行居中。
.parent { height: 200px; width: 100%; background-color: gray; position: relative; } .child { position: absolute; left: 50%; /* margin-left: -50px; */ transform: translateX(-50%); height: 100px; width: 100px; background-color: red; }
图示:
垂直居中
方法一:table-cell + vertical-align
优点:浏览器兼容性好
缺点:vertical-align有继承性,会导致父级元素的文本也垂直居中
1 <style> 2 .parent { 3 display: table-cell; 4 vertical-align: middle; 5 height: 400px; 6 width: 100%; 7 background-color: gray; 8 } 9 .child { 10 height: 100px; 11 width: 100px; 12 background-color: red; 13 } 14 </style>
方法二:absolute + transform
优点:父级元素是否脱离文档流,不影响子元素垂直居中效果
缺点:transform是css3新增属性,对老版本浏览器兼容性不佳
1 <style> 2 .parent { 3 position: relative; 4 height: 400px; 5 width: 100%; 6 background-color: gray; 7 } 8 .child { 9 position: absolute; 10 top: 50%; 11 transform: translateY(-50%); 12 height: 100px; 13 width: 100px; 14 background-color: red; 15 } 16 </style>
图示:

水平垂直居中
方法一:table + margin实现水平,table-cell + vertical-align实现垂直
缺点:父子元素都设置了值,代码可读性差
1 <style> 2 .parent { 3 display: table-cell; 4 vertical-align: middle; 5 height: 400px; 6 width: 1%;/*表格单元比较特殊,100%无法撑起宽度*/ 7 background-color: gray; 8 } 9 .child { 10 display: table; 11 margin: 0 auto; 12 height: 100px; 13 width: 100px; 14 background-color: red; 15 } 16 </style>
方法二:absolute + transform实现水平和垂直
缺点:对不支持css的旧版浏览器兼容性欠佳
1 <style> 2 .parent { 3 position: relative; 4 height: 400px; 5 width: 100%; 6 background-color: gray; 7 } 8 .child { 9 position: absolute; 10 top: 50%; 11 left: 50%; 12 transform: translate(-50%, -50%); 13 height: 100px; 14 width: 100px; 15 background-color: red; 16 } 17 </style>
图示:

这是签名这是签名这是签名这是签名

浙公网安备 33010602011771号