- 本文总结CSS居中,包括水平居中和垂直居中.本文至关于CSS决策树,下次再遇到CSS居中问题时有章可循.
- 参考Centering in CSS: A Complete Guide和【基础】这15种CSS居中的方式,你都用过哪几种
- 本文的引用归原做者全部.
- 代码在线演示工具JSbin使用指南
inline
或inline-*
元素水平居中给须要居中的元素一个block
父元素,须要居中子元素为 文本 或者 inline
, inline-block
, inline-table
, inline-flex
css
核心代码html
.center-children { text-align: center; }
JSbin演示地址
效果:segmentfault
block
元素水平居中父元素为block
,子元素也为bolck
,且子元素设置了宽度(没宽度子元素就继承父元素宽度,居中没有意义).
不管正在居中块级元素的宽度或父级的宽度如何,都会起做用。浏览器
方法:子元素margin: 0 auto;
左右外边距设置为自动填充ide
核心代码工具
.center-me { margin: 0 auto; }
效果:布局
block
元素水平居中block
元素一行排列水平居中inline-block
,原理是将子元素转化为inline-block
.再用text-align: center;
display: flex
.注意:子元素高度会保持一致.看下方例子.核心代码:ui
.inline-block-center { text-align: center; } .inline-block-center div { display: inline-block; text-align: left; } .flex-center { display: flex; justify-content: center; }
效果:spa
block
元素每行一个水平居中由于每一个block
元素独占一行,因此方法仍然是margin: 0 auto;
演示:
垂直居中比较麻烦
inline
或 inline-*
元素单行垂直居中须要垂直居中的元素为单行的inline
或 inline-*
元素,例如一个text或者a连接(包括a连接变化而成的按钮)
padding
(推荐)上下和左右使用相同的padding
能够不用设置宽高,既能够在修改文本内容是自适应,又能够减小出现BUG的概率.
核心代码:
.link { padding-top: 30px; padding-bottom: 30px; }
演示:
line-height
与高度相同核心代码
.center-text-trick { height: 100px; line-height: 100px; white-space: nowrap; /*nowrap文本内的换行无效内容只能在一行显示*/ }
多行文本使用增长上下padding
垂直居中的方法仍然有效且良好,不需设置宽高,推荐使用.
若是这样作不起做用,那么文本所在的元素多是table或者table-cell元素,不管是真正的table仍是后期本身添加的CSS.
下面说说这两种状况使用其余方法的垂直居中.
display: table;
和vertical-align: middle;
核心代码:
.center-table { display: table; } .center-table p { display: table-cell; vertical-align: middle; }
table
+vertical-align: middle
多行文本垂直居中JSbin演示
flex
布局多行文本居中一个flex-child能够简单地在flex-parent的中心.
核心代码
.flex-center-vertically { display: flex; justify-content: center; flex-direction: column; height: 400px; }
block
元素垂直居中block
元素高度原理是绝对定位,top: 50%;
而后 margin-top
设置为负边距且值为他自己高度的一半.
核心代码:
.parent { position: relative; } .child { position: absolute; top: 50%; height: 100px; margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */ }
注意:使用
position: absolute;
绝对定位会使元素脱离文档流
block
元素高度未知垂直居中借助CSS3中的transform
属性向Y轴反向偏移50%的方法实现垂直居中。可是部分浏览器存在兼容性的问题。
核心代码:
.parent { position: relative; } .child { position: absolute; top: 50%; transform: translateY(-50%); }
block
元素高度未知垂直居中核心代码:
.parent { display: flex; flex-direction: column; justify-content: center; }
核心代码:
依旧是绝对定位+宽高一半的负边距
.parent { position: relative; } .child { width: 300px; height: 100px; padding: 20px; position: absolute; top: 50%; left: 50%; margin: -70px 0 0 -170px; }
利用2D变换,在水平和垂直两个方向都向反向平移宽高的一半,从而使元素水平垂直居中。
核心代码
.parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
flex
布局垂直水平居中核心代码:
.parent { display: flex; justify-content: center; align-items: center; }
grid
布局垂直水平居中核心代码:
body, html { height: 100%; display: grid; } span { /* thing to center */ margin: auto; }