.container { display: table-cell; vertical-align: middle; text-align: center; width: 400px; height: 300px; border: 1px solid #ccc; }
.container img { vertical-align: middle; max-width: 100%; max-height: 100%; }
優點:單層結構、垂直置中語義明確。缺點:IE7- 不支援、無法配合 absolute 子元素彈性定位。
.parent { position: relative; width: 300px; height: 200px; border: 1px solid #ccc; }
.child { position: absolute; top: 50%; left: 50%; width: 240px; height: 140px; margin: -70px 0 0 -120px; background: #ccc; }
優點:IE6+ 全支援。缺點:需預知子元素尺寸、結構較深。
.title { height: 55px; line-height: 55px; text-align: center; border: 1px solid #ccc; }
優點:極簡、全瀏覽器支援。缺點:僅限單行文字、高度固定。
.parent { position: relative; width: 300px; height: 200px; border: 1px solid #ccc; }
.child { position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; width: 240px; height: 140px; background: #ccc; }
優點:不需知寬高(若寬高為 auto 需配合具體尺寸)、程式碼簡潔。缺點:IE8- 不支援四向定位 + margin auto。
.center { display: flex; align-items: center; justify-content: center; min-height: 200px; }
優點:單層、不需知尺寸、支援多行、響應式友善。缺點:IE10 需 -ms- 前綴,IE9- 不支援。
.center { display: grid; place-items: center; min-height: 200px; }