最常見的是 text-align: center,適合行內文字或行內元素;若是區塊元素,可用 margin: 0 auto 搭配固定寬度。
單行文字可用 line-height 等於 height;多行內容可考慮 vertical-align: middle 搭配 display: table 與 table-cell,或使用 Flexbox。
給父容器 position: relative,子元素使用 position: absolute,並設定 top、left、bottom、right 與 margin: auto,可讓元素置中。若內容可能溢出,建議加上 overflow: auto。
.Absolute-Center {
width: 50%;
height: 50%;
overflow: auto;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
若要把元素固定在畫面中央,可將 position 改為 fixed,並加上 z-index。
使用百分比寬高、min-width、max-height 可做出響應式置中;透過 top、right、bottom、left 可調整偏移;若內容過高,可用 overflow: auto 或 max-height 避免溢出。
top: 50%; left: 50%; transform: translate(-50%, -50%) 是很靈活的做法,因為百分比位移是依元素自身尺寸計算,適合未知寬高的內容。
若已知寬高,可用負 margin 置中;若高度可變,可用表格儲存格或 display: table-cell 讓內容垂直居中。
現代版面最推薦的方式之一是 Flexbox:在容器設定 display: flex、align-items: center、justify-content: center,即可同時完成水平與垂直置中。
沒有一種置中寫法絕對最好,真正要做的是依內容尺寸、瀏覽器支援與維護成本,選擇最適合的方案。