萬盛學電腦網

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

CSS 讓 DIV 水平垂直置中的多種實現方法

前言

「置中」是 CSS 佈局最常見也最讓新手頭痛的需求。本文整理水平置中、垂直置中、水平垂直同時置中的多種方案,涵傳統相容寫法與現代 Flex/Grid 最佳實踐。

一、區塊水平置中

定寬區塊:margin auto

.center-box {
  width: 600px;
  margin-left: auto;
  margin-right: auto;
}

/* 簡寫 */
.center-box { width: 600px; margin: 0 auto; }

原理:左右 margin 設為 auto,瀏覽器自動分配剩餘空間。

不定寬區塊:text-align center(行內/行內區塊)

.parent { text-align: center; }
.child { display: inline-block; }

二、垂直置中

單行文字:line-height = height

.single-line {
  height: 50px;
  line-height: 50px;
}

多行文字/區塊:Flex(推薦)

.parent {
  display: flex;
  align-items: center; /* 垂直置中 */
  justify-content: center; /* 水平置中 */
  height: 300px;
}

Grid 置中(最簡潔)

.parent {
  display: grid;
  place-items: center; /* 同時水平垂直置中 */
  height: 300px;
}

傳統絕對定位 + transform(相容 IE10+)

.parent { position: relative; height: 300px; }
.child {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
}

絕對定位 + margin auto(需定寬高)

.parent { position: relative; height: 300px; }
.child {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  width: 200px; height: 100px;
  margin: auto;
}

三、圖片在 DIV 中垂直置中

背景圖片法

.bg-center {
  background: url(img.jpg) no-repeat center center;
  background-size: cover; /* 或 contain */
  height: 200px;
}

Flex/Grid 置中 img 元素

.img-box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}
.img-box img { max-width: 100%; max-height: 100%; }

四、IE 相容性補充

  • IE6-7 不支援 margin: auto 置中絕對定位元素,需搭配 text-align: center 於父層。
  • Flex 需 IE10+(加 -ms- 前綴),Grid 需 IE 不支援(可用 Polyfill)。
  • 現代專案建議採用 Flex/Grid,並以 @supports 或 Polyfill 兼容舊瀏覽器。

五、完整範例:水平垂直雙向置中卡片

<div class="modal-overlay">
  <div class="modal-card">內容</div>
</div>

結語

現代 CSS 以 Flexbox 與 Grid 解決置中問題最優雅、代碼最少。掌握 place-items: center 或 align-items + justify-content,即可應對絕大多數置中場景。舊專案維護時,transform: translate(-50%, -50%) 是相容性最好的傳統方案。

copyright © 萬盛學電腦網 all rights reserved