垂直居中在「高度已知」時很簡單,但如果內容高度不確定(例如圖片尺寸由後端決定),就需要換個思路。以下兩個範例都用 display: table-cell 搭配 vertical-align: middle 來處理。
/* center < */
.vetically {
vertical-align: middle;
display: table-cell;
*position: relative;
}
.vetically_C {
display: block;
margin: 0 auto;
text-align: center;
*position: absolute;
*top: 50%;
*left: 50%;
*margin-top: expression(-(this.height) / 2);
*margin-left: expression(-(this.width) / 2);
}
/* center > */
標準瀏覽器靠 table-cell + vertical-align 就能完美居中;IE6/7 不支援 table-cell,因此用星號 hack 加上絕對定位,再用 expression 讀取元素自身的寬高,動態算出負一半的 margin 把它拉回中心。
要留意 expression 是 IE 私有且效能不佳的寫法,只適合無可奈何的相容情境。
標準瀏覽器做法相同,差別在 IE6/IE7 的處理——在 img 前面插入一對空標籤,讓它撐滿容器高度並垂直居中,圖片再對齊到同一條基線:
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>方法2 - 未知高度的圖片垂直居中</title>
<style type="text/css">
body {
height: 100%;
}
#box{
width: 500px;
height: 400px;
display: table-cell;
text-align: center;
vertical-align: middle;
border: 1px solid #d3d3d3;
background: #fff;
}
#box img{
border: 1px solid #ccc;
}
</style>
<!--[if IE]>
<style type="text/css">
#box i {
display: inline-block;
height: 100%;
vertical-align: middle
}
#box img {
vertical-align: middle
}
</style>
<![endif]-->
</head>
<body>
<div id="box">
<i></i><img src="images/demo_zl.png" alt="" />
</div>
</body>
</html>
原理是:讓空白的 <i> 撐滿 100% 高度並垂直居中,由於它與圖片同屬 inline-block,兩者會落在同一條中線上,圖片自然就跟著居中了。
今天如果不必支援 IE,最簡潔的方案是 Flexbox,只要三行:
.box {
display: flex;
align-items: center;
justify-content: center;
height: 400px;
}
或者用 Grid:
.box {
display: grid;
place-items: center;
height: 400px;
}
兩者都不需要知道子元素的實際尺寸,也不需要 hack,這正是 CSS 標準演進最值得高興的地方。