一起搞懂 CSS 水平居中與垂直居中的16個方法

一起搞懂 CSS 水平居中與垂直居中的16個方法

一、水平居中

1.1 行內元素

。parent { text-align: center;}

1.2 塊級元素

1。2。1 塊級元素一般居中方法

。son { margin: 0 auto;}

1。2。2 子元素含 float

。parent{ width:fit-content; margin:0 auto;}。son { float: left;}

1。2。3 Flex 彈性盒子

1) flex 2012版

。parent { display: flex; justify-content: center;}

2)flex 2009版

。parent { display: box; box-orient: horizontal; box-pack: center;}

1。2。4 絕對定位

1)transform

。son { position: absolute; left: 50%; transform: translate(-50%, 0);}

2)left: 50%

。son { position: absolute; width: 寬度; left: 50%; margin-left: -0。5*寬度}

3)left/right: 0

。son { position: absolute; width: 寬度; left: 0; right: 0; margin: 0 auto;}

小結

以上是 CSS 水平居中的 8 種方法。

二、垂直居中

2.1 行內元素

。parent { height: 高度;}。son { line-height: 高度;}

注:① 子元素 line-height 值為父元素 height 值。② 單行文字。

2.2 塊級元素

2。2。1 行內塊級元素

。parent::after, 。son{ display:inline-block; vertical-align:middle;}。parent::after{ content:‘’; height:100%;}

適應 IE7。

2。2。2 table

。parent { display: table;}。son { display: table-cell; vertical-align: middle;}

優點

元素高度可以動態改變, 不需再CSS中定義, 如果父元素沒有足夠空間時, 該元素內容也不會被截斷。

缺點

IE6~7, 甚至IE8 beta中無效。

2。2。3 Flex 彈性盒子

1)flex 2012版

。parent { display: flex; align-items: center;}

優點

內容塊的寬高任意, 優雅的溢位。

可用於更復雜高階的佈局技術中。

缺點

IE8/IE9不支援。

需要瀏覽器廠商字首。

渲染上可能會有一些問題。

2)flex 2009版

。parent { display: box; box-orien: vertical; box-pack: center;}

優點

實現簡單, 擴充套件性強。

缺點

相容性差, 不支援IE。

2。2。4 絕對定位

1)transform

。son { position: absolute; top: 50%; transform: translate( 0, -50%);}

優點

程式碼少。

缺點

IE8不支援, 屬性需要追加瀏覽器廠商字首, 可能干擾其他 transform 效果, 某些情形下會出現文字或元素邊界渲染模糊的現象。

2)top: 50%

。son { position: absolute; top: 50%; height: 高度; margin-top: -0。5高度;}

優點

適用於所有瀏覽器。

缺點

父元素空間不夠時, 子元素可能不可見(當瀏覽器視窗縮小時,捲軸不出現時)。如果子元素設定了overflow:auto, 則高度不夠時, 會出現捲軸。

3)top/bottom: 0;

。son { position: absolute; top: 0; botton: 0; margin: auto 0;}

優點

簡單。

缺點

沒有足夠空間時, 子元素會被截斷, 但不會有捲軸。

小結

以上是 CSS 垂直居中的 8 種方法及其優缺點。

連結:https://juejin。im/post/5c8f9e595188252db756920c

作者:Agoreal