當元素寬高固定時,最經典的絕對居中方法是「定位 50% + 負 margin 一半尺寸」。
.content {
width: 400px;
height: 300px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -200px; /* 寬度一半 */
margin-top: -150px; /* 高度一半 */
background: #8888cc;
}
left:50%; top:50% 將元素左上角對齊視窗中心點。margin-left、margin-top 向左上拉回自身高寬一半,使幾何中心與視窗中心重合。body,需設定 position:relative/absolute/fixed 建立定位基準。<!DOCTYPE html>
<html><head><title>固定寬高元素居中示例</title>
<style>
.content { /* 上述 CSS */ }
</style></head>
<body>
<div class="content"><p>指定頁面居中的元素</p></div>
</body></html>
box-sizing:border-box。.parent { display:flex; justify-content:center; align-items:center; height:100vh; }
.parent { display:grid; place-items:center; height:100vh; }
.content { position:absolute; left:50%; top:50%; transform:translate(-50%,-50%); }