實現彈窗/模態框在視口水平垂直居中,是前端高頻需求。本文對比傳統 document.body.clientWidth 寫法與現代 CSS Flex/Grid + transform 方案,給出最佳實踐代碼。
function centerPopup(el) {
const w = el.offsetWidth;
const h = el.offsetHeight;
// 視口尺寸
const vw = document.documentElement.clientWidth;
const vh = document.documentElement.clientHeight;
// 滾動偏移
const scrollX = window.pageXOffset || document.documentElement.scrollLeft;
const scrollY = window.pageYOffset || document.documentElement.scrollTop;
el.style.position = 'absolute';
el.style.left = scrollX + (vw - w) / 2 + 'px';
el.style.top = scrollY + (vh - h) / 2 + 'px';
}
// 使用
const popup = document.getElementById('popup');
centerPopup(popup);
window.addEventListener('resize', () => centerPopup(popup));
window.addEventListener('scroll', () => centerPopup(popup));
缺點:需監聽 resize/scroll、預先知道彈窗尺寸、滾動時會閃爍。
.modal-overlay {
position: fixed; inset: 0; // 覆蓋全視口
display: flex; align-items: center; justify-content: center;
background: rgba(0,0,0,.5);
}
.modal-content {
background: #fff; padding: 20px; border-radius: 8px;
max-width: 90vw; max-height: 90vh; overflow: auto;
}
彈窗內容自動居中,**無需任何 JS 計算**,滾動、縮放自動適配。
.modal-content {
position: fixed;
left: 50%; top: 50%;
transform: translate(-50%, -50%);
/* 其餘樣式同方案一 */
}
適用於彈窗不在 body 直系、或需嵌套在其他定位上下文中的情況。
若彈窗內容由異步數據決定,尺寸在渲染後才確定:
centerPopup(),或使用 ResizeObserver 監聽尺寸變化自動重新定位。const ro = new ResizeObserver(() => centerPopup(popup));
ro.observe(popup);
// 銷毀時 ro.disconnect();
role="dialog"、aria-modal="true"、aria-labelledby 指向標題。| 場景 | 推薦方案 |
|---|---|
| 現代項目(IE10+) | CSS fixed + transform 或 flex,零 JS 計算 |
| 需支持 IE8/9 | JS 計算 + position:absolute + resize/scroll 監聽 |
| 嵌套定位上下文/非 fixed | absolute + transform |
| 動態尺寸/異步內容 | CSS 方案自動適配;JS 方案配合 ResizeObserver |
拋棄手動計算 clientWidth/2 - offsetWidth/2,擁抱 CSS 佈局能力,才是 2024+ 的正解。