萬盛學電腦網

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

DIV 文字絕對居中:水平垂直雙向居中最簡方案

實現文字在 div 中水平垂直雙向居中,不再需要複雜的表格佈局。掌握 text-align 與 line-height 黄金組合,輕鬆搞定單行文字居中。

核心代碼:兩行 CSS 搞定

.absolute-center {
  height: 50px;              /* 固定高度 */
  line-height: 50px;         /* 行高 = 高度 → 垂直居中 */
  text-align: center;        /* 水平居中 */
  /* 可選:防止文字溢出 */
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

HTML 結構

<div class="absolute-center">完美居中的文字內容</div>

原理解析

屬性 作用機制 適用範圍
text-align: center 控制行內/行內塊級元素水平對齊 所有瀏覽器,所有行內內容
line-height = height 行框高度等於容器高度,文字在行框中垂直居中 單行文字、單行行內元素

局限性與進階方案

⚠️ 僅限單行文字

多行文字會導致行高疊加,破壞垂直居中。多行居中請用:

方案一:Flexbox(現代首選)

.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

方案二:Grid(二維佈局)

.grid-center {
  display: grid;
  place-items: center;  /* 等同 align-items + justify-items */
  height: 200px;
}

方案三:絕對定位 + Transform(兼容 IE9+)

.absolute-center {
  position: relative;
  height: 200px;
}
.absolute-center > span {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

方案四:表格佈局(兼容 IE8+)

.table-center {
  display: table;
  height: 200px;
  width: 100%;
}
.table-center > span {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

選擇指南

  • 單行文字、固定高度:line-height = height 最簡潔高效
  • 多行文字、不固定高度:Flexbox/Grid 現代首選
  • 需兼容 IE8/9:Transform 方案或表格佈局
  • 圖文混排垂直居中:Flexbox align-items: center
copyright © 萬盛學電腦網 all rights reserved