萬盛學電腦網

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

CSS 任意尺寸圖片垂直置中 5 大方案:Flex、Grid、Table-Cell、偽元素、Absolute+Transform 完整對比

核心挑戰

圖片為替換元素,預設 inline 行為但有固有尺寸。垂直置中需解決:容器高度已知/未知、圖片尺寸已知/未知、多行文字混排、響應式適配。

方案對比總覽

方案容器高度圖片尺寸瀏覽器支援複雜度推薦指數
Flexbox任意任意IE10+極低⭐⭐⭐⭐⭐
Grid任意任意現代瀏覽器極低⭐⭐⭐⭐⭐
Table-Cell任意任意IE8+低⭐⭐⭐⭐
偽元素輔助已知任意IE8+中⭐⭐⭐
Absolute + Transform已知任意IE9+中⭐⭐⭐
Absolute + 負 Margin已知已知全瀏覽器低⭐⭐

方案詳解與代碼

1. Flexbox(現代首選)

.img-center-flex {
  display: flex;
  align-items: center;      /* 垂直置中 */
  justify-content: center;  /* 水平置中 */
  min-height: 300px;        /* 容器需有高度 */
}
.img-center-flex img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;      /* 保持比例縮放 */
}

2. Grid(最語義簡潔)

.img-center-grid {
  display: grid;
  place-items: center;      /* 同時水平垂直置中 */
  min-height: 300px;
}
.img-center-grid img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

3. Table-Cell(IE8+ 相容方案)

.img-center-table {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  height: 300px;            /* 必須固定高度 */
  width: 400px;             /* 可選 */
}
.img-center-table img {
  vertical-align: middle;
  max-width: 100%;
  max-height: 100%;
}

4. 偽元素輔助(IE8+、無需改變容器 display)

.img-center-ghost {
  text-align: center;
  height: 300px;            /* 容器固定高度 */
}
.img-center-ghost::before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
.img-center-ghost img {
  display: inline-block;
  vertical-align: middle;
  max-width: 100%;
  max-height: 100%;
}

5. Absolute + Transform(已知容器高度、圖片未知尺寸)

.img-center-absolute {
  position: relative;
  height: 300px;
}
.img-center-absolute img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 100%;
  max-height: 100%;
}

進階:響應式圖片容器(保持比例、垂直置中、不溢出)

.responsive-img-container {
  position: relative;
  width: 100%;
  padding-top: 75%;         /* 4:3 比例容器 */
  overflow: hidden;
}
.responsive-img-container img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

object-fit 關鍵屬性

值行為適用場景
contain完整顯示、保持比例、可能留白圖片展示、Logo、頭像
cover填滿容器、保持比例、裁切溢出背景圖、Banner、卡片封面
fill拉伸填滿、不保持比例極少用
none原始尺寸、不縮放精確像素控制
scale-down取 none 或 contain 较小者防止放大失真

選型決策指南

  1. 現代專案、容器高度動態 → Flex(一維)或 Grid(二維)。
  2. 需支援 IE8-10 → Table-Cell 或 偽元素輔助。
  3. 圖片需疊層、絕對定位特效 → Absolute + Transform。
  4. 響應式比例容器 → padding-top 比例 + Absolute 圖片。
  5. 避免 負 Margin 方案(需知圖片尺寸、不響應式)。

無障礙與 SEO 提示

  • 始終提供 alt 屬性描述圖片內容。
  • 裝飾性圖片用 alt="" 或 CSS 背景圖。
  • object-fit 不影響 SEO,圖片仍被索引。

總結

任意尺寸圖片垂直置中,**現代首選 Flex/Grid**,**舊環境用 Table-Cell/偽元素**,**特殊定位需求用 Absolute+Transform**。關鍵在於容器是否有高度、是否需響應式、瀏覽器支援基線。善用 object-fit 控制縮放行為,配合 max-width/height: 100% 防止溢出,建立專案通用 .img-center、.img-cover 工具類。

copyright © 萬盛學電腦網 all rights reserved