/* 父容器 */
body { text-align: center; } /* IE5.x 相容 */
/* 子容器 */
#center { margin-left: auto; margin-right: auto; width: 940px; }
width。DOCTYPE 觸發標準模式。div,各層加 margin:auto,避免單層過寬。#center {
height: 200px;
line-height: 200px; /* 等於容器高度 */
vertical-align: middle;
text-align: center;
}
將行高撐滿容器,行內內容自動垂直置中。僅限單行。
body { background: url(bg.jpg) #fff no-repeat center; }
center 關鍵字同時水平垂直置中背景圖。可用 top left、50% 30% 等精確控制。
<div id="L1" style="position:absolute;">內容</div>
<script>
function moveIt() {
L1.style.left = (document.body.offsetWidth - L1.offsetWidth) / 2 + document.body.scrollLeft;
L1.style.top = (document.body.offsetHeight - L1.offsetHeight) / 2 + document.body.scrollTop;
}
window.onload = window.onresize = window.onscroll = moveIt;
</script>
適用於彈窗、Loading 等需隨時置中的絕對定位層。
#box {
position: absolute;
left: 50%; top: 50%;
width: 740px; height: 340px;
margin-left: -370px; /* -width/2 */
margin-top: -170px; /* -height/2 */
background: #f00;
}
原理: 左上角對齊視窗中心 → 負邊距拉回自身高寬一半 → 幾何中心重合。缺點: 需知寬高,內容超出會溢出。
.center-container {
display: flex;
justify-content: center; /* 水平 */
align-items: center; /* 垂直 */
min-height: 100vh; /* 全螢幕高 */
}
IE10+ 完美支援,無需知寬高、無溢出風險、代碼最少。現代專案首選。