垂直居中向來是 CSS 的經典題目。當容器與內容尺寸都確定時,寫法很多;但一旦高度不確定,就需要換個思路。下面提供兩種實用方案。
思路是先把元素的左上角對齊父容器的正中點,再用 top:-50%; left:-50% 把自己往左上拉回一半。要注意的是,這裡的百分比是相對於元素自身的尺寸計算的,所以能在不知具體高度的情況下完成居中。
<!DOCTYPE html> <html> <meta name="name" content="content" charset='utf-8'> <head> <title>網頁居中</title> </head> <style type="text/css" media="screen"> *{margin:0;padding: 0;} .al{width: 800px;height: 600px;margin: 30px auto;position: relative;border:1px solid red;} .par{position: absolute;top:50%;left:50%;} .chd{background: green;position: relative;top:-50%;left:-50%;} .ul{width: 600px;height:400px;margin: 10px auto;border:1px solid blue; } .ul li{width: 50px;height: 30px;border:1px solid red;text-align: center;line-height: 30px;list-style-type: none;float:left;margin: 20px 0 0 20px;} </style> <body> <div class="al"> <div class="par"> <div class="chd"> 我要居中我要居中 </div> </div> </div> </body> </html>
把父容器設為 display: table-cell 並加上 vertical-align: middle 與 text-align: center,子元素則用 display: inline-block。這種做法不需要任何負值位移,也不必知道內容高度,程式碼最為乾淨。
<!DOCTYPE html> <html> <meta name="name" content="content" charset='utf-8'> <head> <title>網頁居中</title> </head> <style type="text/css" media="screen"> *{margin:0;padding: 0;} .al{width: 800px;height: 600px;margin: 30px auto;} .par{width: 800px;height: 600px;border:1px solid red;display: table-cell;text-align: center;vertical-align: middle;} .chd{background: green;display: inline-block;} </style> <body> <div class="al"> <div class="par"> <div class="chd"> 我要居中我要居中 </div> </div> </div> </body> </html>
如果專案不必支援老舊瀏覽器,Flexbox 只需在父容器寫上 display:flex; justify-content:center; align-items:center; 即可;Grid 則用 display:grid; place-items:center;。兩者都能在內容高度完全未知的情況下完成居中,且程式碼量最少。