萬盛學電腦網

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

CSS 讓文字靠近容器底部對齊:relative + absolute 定位法

核心技巧:父相對、子絕對、bottom:0

.container {
  position: relative;        /* 建立定位基準 */
  width: 300px; height: 300px;
  border: 1px solid #333;
  text-align: center;        /* 水平置中 */
}

.container p {
  position: absolute;
  bottom: 0;                 /* 靠父層底部 */
  left: 0; right: 0;         /* 水平撐滿 */
  margin: 0; padding: 0;     /* 重置預設間距 */
}

完整 HTML 範例

<!DOCTYPE html>
<html>
<head>
  <meta charset="gb2312">
  <title>文字底部對齊示範</title>
  <style>
    #txt {
      width: 300px; height: 300px;
      border: 1px solid #333;
      text-align: center;
      position: relative;
    }
    #txt p {
      position: absolute;
      bottom: 0; left: 0; right: 0;
      margin: 0; padding: 0;
    }
  </style>
</head>
<body>
  <div id="txt">
    <p>這段文字緊貼容器底部</p>
  </div>
</body>
</html>

關鍵點

  • 父層 position:relative 建立定位參考系,自身不偏移。
  • 子層 position:absolute; bottom:0 相對父層底部對齊。
  • left:0; right:0 配合 text-align:center 實現水平置中。
  • 精確控制距離:bottom: 10px 即為離底 10px。

現代替代:Flexbox

.container {
  display: flex;
  flex-direction: column;
  justify-content: flex-end; /* 垂直靠底 */
  align-items: center;       /* 水平置中 */
  height: 300px;
}

語意更清晰、無絕對定位副作用,現代專案首選。

copyright © 萬盛學電腦網 all rights reserved