固定尺寸元素絕對置中是 Modal、彈窗、Loading 遮罩的經典需求。核心公式:top: 50%; left: 50%; margin-top: -height/2; margin-left: -width/2;。
<!DOCTYPE html>
<html>
<head>
<title>固定寬高絕對置中示例</title>
<style>
.content {
width: 400px; height: 300px;
position: absolute;
left: 50%; top: 50%;
margin-left: -200px; /* -width/2 */
margin-top: -150px; /* -height/2 */
background-color: #8888CC;
}
</style>
</head>
<body>
<div class="content"><p>置中元素內容</p></div>
</body>
</html>
max-width 配合 JS 計算)。position: absolute 或 fixed(相對視窗置中)。relative/absolute/fixed,則相對父層置中;否則相對 <body>。border,需在 margin 扣除 border 寬度:margin-left: -(width/2 + border-left)。.h-center { position: absolute; left: 50%; margin-left: -200px; }
.fixed-center { position: fixed; left: 50%; top: 50%; margin: -150px 0 0 -200px; }
/* Flexbox */
.center { display: flex; align-items: center; justify-content: center; height: 100vh; }
/* Grid */
.center { display: grid; place-items: center; height: 100vh; }
/* Transform(支援未知尺寸) */
.center {
position: absolute; top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
Transform 方案 為現代專案首選:無需預知尺寸、支援動畫、程式碼最少。IE10+ 支援,IE9 以下需 Polyfill 或退回負 margin 方案。