萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

固定寬高 DIV 絕對置中:原理、代碼與實戰細節

固定尺寸元素絕對置中是 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>

關鍵條件

  1. 元素 必須有固定寬高(或 max-width 配合 JS 計算)。
  2. position: absolute 或 fixed(相對視窗置中)。
  3. 父層若為 relative/absolute/fixed,則相對父層置中;否則相對 <body>。
  4. 若有 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 方案。

copyright © 萬盛學電腦網 all rights reserved