使用CSS2,CSS3和Flexbox实现:内联元素、块级元素和超过一个的块级元素的水平居中;一行或多行内联元素、知道元素高度和不知道元素高度的块级元素的垂直居中;固定高度和宽度的元素、不确定高度和宽度的元素的水平垂直居中。
水平居中
内联、内联块状元素等
inline或者inline-*:例如文本或链接,可以直接在块级父元素内居中。这可以用于有inline
,inline-block
, inline-table
, inline-flex
等属性的元素上。
|
|
See the Pen Centering Inline Elements by icke (@ickedesign) on CodePen.
块级元素
将该块级元素的margin-left
和margin-right
属性设置为aoto(需要为其设置宽度,否则可能占满整行不需要居中),通常简单的记成:
|
|
See the Pen Centering Single Block Level Element by icke (@ickedesign) on CodePen.
对于一个固定了宽度的块级元素或者其父元素这样使用都没什么问题。
超过一个的块级元素
如果有两个或者更多的块级元素需要被水平居中,那最好改变元素的display属性,以下例子是将其设为inline-block和flex的:
See the Pen Centering Row of Blocks by icke (@ickedesign) on CodePen.
如果是多个块级元素层层叠加在一起的,在这种情况下使用margin:auto;
的方法仍然行得通:
See the Pen Centering Blocks on Top of Each Other by icke (@ickedesign) on CodePen.
垂直居中
内联、内联块状元素等
inline或者inline-*
只有一行
一些内联/文本(inline/text)元素能垂直居中仅仅是因为他们有相同的上下内边距(padding)
|
|
如果出于某些原因不能去操作padding,并且你知道将要操作的元素不会换行,那么只要让元素的line-height和height相同即可
|
|
多行
如果元素处于表格单元中(无论表面上或者用css属性),垂直居中多行,可以使用vertival-align,它不会像普通的元素垂直居中一行。
See the Pen Vertical Center Multi Lines of Text by icke (@ickedesign) on CodePen.
使用flexbox:
|
|
See the Pen Vertical Center Multi Lines of Text with Flexbox by icke (@ickedesign) on CodePen.
块级元素
知道元素的高度
|
|
See the Pen Center Block with Fixed Height by icke (@ickedesign) on CodePen.
不知道元素的高度
|
|
See the Pen Center Block with Unknown Height by icke (@ickedesign) on CodePen.
也可以使用Flexbox:
|
|
水平垂直居中
元素固定高度和宽度
|
|
See the Pen Center Block with Fixed Height and Width by icke (@ickedesign) on CodePen.
元素不确定高度和宽度
|
|
See the Pen Center Block with Unknown Height and Width by icke (@ickedesign) on CodePen.
Flexbox
|
|
See the Pen Center Block with Unknown Height and Width with Flexbox by icke (@ickedesign) on CodePen.