.wrapper { display: table; width: 500px; height: 500px; }
.row { display: table-row; }
.cell { display: table-cell; vertical-align: middle; }
優點:不需知道內容高度。缺點:IE6/7 不支援,結構較繁瑣。
.wrapper { position: relative; width: 500px; height: 500px; }
.content { position: absolute; top: 50%; left: 0; width: 400px; height: 300px; margin-top: -150px; }
優點:相容性最好。缺點:必須知道內容高度。
.wrap { height: 500px; }
.additional { height: 50%; margin-bottom: -120px; } /* 內容高度一半 */
#content { height: 240px; }
缺點:需額外標籤、同樣需知高度。
.content {
position: absolute; top: 0; bottom: 0; left: 0; right: 0;
margin: auto; width: 70%; height: 240px;
}
優點:程式碼極簡。缺點:IE6/7 不支援、需固定高寬。
.single-line { height: 50px; line-height: 50px; }
僅適用單行文字。
.wrapper { display: flex; align-items: center; justify-content: center; height: 500px; }
/* 或 */
.wrapper { display: grid; place-items: center; height: 500px; }