萬盛學電腦網

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

DIV 文字絕對水平垂直置中:Flexbox 現代解法、Line-height 單行技巧、Transform 相容方案

核心場景分類

場景推薦方案關鍵代碼
單行文字、固定高度容器Line-height 大法height: 50px; line-height: 50px; text-align: center;
多行文字/未知尺寸、現代瀏覽器Flexbox 置中display: flex; justify-content: center; align-items: center;
多行文字/未知尺寸、需支援 IE9+Absolute + Transformposition: absolute; top:50%; left:50%; transform: translate(-50%, -50%);
表格儲存格Vertical-aligndisplay: table-cell; vertical-align: middle; text-align: center;
Grid 佈局區域Grid 置中display: grid; place-items: center;

方案詳解

1. Line-height 單行置中(最輕量、相容 IE6+)

.single-line-center {
  height: 50px;
  line-height: 50px;  /* 必須等於固定高度 */
  text-align: center; /* 水平置中 */
  white-space: nowrap; /* 防換行破壞 */
  overflow: hidden;
  text-overflow: ellipsis; /* 內容過長截斷 */
}

⚠️ 多行文字會失效(行高疊加),僅限單行、不換行場景。

2. Flexbox 雙向置中(現代標準,推薦)

.flex-center {
  display: flex;
  justify-content: center;  /* 主軸(水平)置中 */
  align-items: center;      /* 交叉軸(垂直)置中 */
  min-height: 100vh;        /* 全螢幕示例 */
  text-align: center;       /* 多行文字內部水平置中 */
}
  • 子元素無需任何定位屬性,純內容置中。
  • 支援多行文字、動態高度、響應式縮放。
  • IE10+ 需 -ms-flexbox 前綴,Autoprefixer 自動處理。

3. Absolute + Transform(相容 IE9+,不需知尺寸)

.absolute-center {
  position: relative;  /* 父容器建立定位基準 */
  min-height: 200px;
}
.absolute-center .content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;  /* 內部文字水平置中 */
  max-width: 90%;      /* 防止超出容器 */
}
  • 優點:不需知道寬高、支援動畫過渡。
  • 缺點:建立堆疊上下文、可能文字模糊、父級需相對定位。

4. Grid 置中(最語義化)

.grid-center {
  display: grid;
  place-items: center;  /* 一行搞定雙向置中 */
  min-height: 100vh;
}

原文範例改良版

原文:<div style="line-height:50px;height:50px; padding:10px;" align="center">

問題:align="center" 為 HTML4 廢棄屬性、padding 會增加實際高度導致垂直偏移。

/* 改良版:純 CSS、語義化、無副作用 */
.center-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  padding: 0 10px;  /* 水平內距,不影響垂直置中 */
  background: #f5f5f5;
  border-radius: 4px;
}

/* 內容自動雙向置中,支援多行自動換行 */
.center-box span { text-align: center; }

自適應高度垂直置中:Flex/Grid 原生支援

原文提到「暫時想不到自適應高度解決方案」,現代答案就是 Flex/Grid:容器給 min-height,內容高度變化時自動保持置中,零 JS、零計算。

總結

DIV 文字絕對置中:單行用 line-height、多行/未知尺寸用 Flex/Grid、相容 IE9 用 Absolute+Transform。建立統一工具類(.flex-center、.grid-center、.absolute-center),專案全域複用。拋棄 align="center"、padding 干擾高度、固定尺寸負邊距等歷史包袱,擁抱現代佈局原生置中能力。

copyright © 萬盛學電腦網 all rights reserved