「置中」是 CSS 佈局最常見也最讓新手頭痛的需求。本文整理水平置中、垂直置中、水平垂直同時置中的多種方案,涵傳統相容寫法與現代 Flex/Grid 最佳實踐。
.center-box {
width: 600px;
margin-left: auto;
margin-right: auto;
}
/* 簡寫 */
.center-box { width: 600px; margin: 0 auto; }
原理:左右 margin 設為 auto,瀏覽器自動分配剩餘空間。
.parent { text-align: center; }
.child { display: inline-block; }
.single-line {
height: 50px;
line-height: 50px;
}
.parent {
display: flex;
align-items: center; /* 垂直置中 */
justify-content: center; /* 水平置中 */
height: 300px;
}
.parent {
display: grid;
place-items: center; /* 同時水平垂直置中 */
height: 300px;
}
.parent { position: relative; height: 300px; }
.child {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
.parent { position: relative; height: 300px; }
.child {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
width: 200px; height: 100px;
margin: auto;
}
.bg-center {
background: url(img.jpg) no-repeat center center;
background-size: cover; /* 或 contain */
height: 200px;
}
.img-box {
display: flex;
align-items: center;
justify-content: center;
height: 200px;
}
.img-box img { max-width: 100%; max-height: 100%; }
margin: auto 置中絕對定位元素,需搭配 text-align: center 於父層。-ms- 前綴),Grid 需 IE 不支援(可用 Polyfill)。@supports 或 Polyfill 兼容舊瀏覽器。<div class="modal-overlay">
<div class="modal-card">內容</div>
</div>
現代 CSS 以 Flexbox 與 Grid 解決置中問題最優雅、代碼最少。掌握 place-items: center 或 align-items + justify-content,即可應對絕大多數置中場景。舊專案維護時,transform: translate(-50%, -50%) 是相容性最好的傳統方案。