當元素的寬高未知時,要實現水平垂直居中會棘手一些。以下整理四種方法,並分析各自的優缺點。
思路:將父元素設為 table、子元素設為 table-cell,就能使用 vertical-align: center 實現垂直居中,再搭配 text-align 實現水平居中。
優點:父元素可以動態改變高度(table 元素的特性)。
缺點:IE8 以下不支援。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>未知寬高元素水平垂直居中</title> </head> <style> .parent1{ display: table; height:300px; width: 300px; background-color: #FD0C70; } .parent1 .child{ display: table-cell; vertical-align: middle; text-align: center; color: #fff; font-size: 16px; } </style> <body> <div class="parent1"> <div class="child">hello world-1</div> </div> </body> </html>
思路:用一個空的 span 標籤,將其 vertical-align 基線設為中間,並設為 inline-block、寬度為 0。
缺點:多了一個無用的空標籤,display:inline-block 在 IE6/7 不支援(需加上 _zoom:1;*display:inline)。當然也可以用偽元素代替 span,只是 IE 支援也不好。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>未知寬高元素水平垂直居中</title> </head> <style> .parent2{ height:300px; width: 300px; text-align: center; background: #FD0C70; } .parent2 span{ display: inline-block; width: 0; height: 100%; vertical-align: middle; zoom: 1;/*BFC*/ *display: inline; } .parent2 .child{ display: inline-block; color: #fff; zoom: 1;/*BFC*/ *display: inline; } </style> <body> <div class="parent1"> <div class="child">hello world-1</div> </div> <div class="parent2"> <span></span> <div class="child">hello world-2</div> </div> </body> </html>
思路:子元素絕對定位,距頂部 50%、左側 50%,再使用 CSS3 的 transform:translate(-50%, -50%)。
優點:寫法簡潔,可在 webkit 內核瀏覽器中使用。
缺點:IE9 以下不支援 transform 屬性。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>未知寬高元素水平垂直居中</title> </head> <style> .parent3{ position: relative; height:300px; width: 300px; background: #FD0C70; } .parent3 .child{ position: absolute; top: 50%; left: 50%; color: #fff; transform: translate(-50%, -50%); } </style> <body> <div class="parent3"> <div class="child">hello world-3</div> </div> </body> </html>
思路:使用 CSS3 的 flex 伸縮布局。
優點:簡單快捷。
缺點:相容性還有提升空間,詳情可參考 caniuse.com。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>未知寬高元素水平垂直居中</title> </head> <style> .parent4{ display: flex; justify-content: center; align-items: center; width: 300px; height:300px; background: #FD0C70; } .parent4 .child{ color:#fff; } </style> <body> <div class="parent4"> <div class="child">hello world-4</div> </div> </body> </html>