text-align 文本对齐

学习

text-align 文本对齐

2026-02-23/0/ 编辑


text-align 文本对齐

基本语法

text-align: 对齐方式;

属性值

说明
left左对齐(默认)
center居中对齐
right右对齐
justify两端对齐
inherit继承父元素

示例代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>text-align 文本对齐</title>
  <style>
    .center {
      /* 行内内容(例如文字、图片、行内块级元素) */
      text-align: center;
    }
    .left {
      text-align: left;  /* 居左是默认值 */
    }
    .right {
      text-align: right;
    }
    .justify {
      text-align: justify;
    }
  </style>
</head>
<body>
  <div class="left">左对齐文字</div>
  <div class="center">居中对齐文字</div>
  <div class="right">右对齐文字</div>
  <div class="justify">两端对齐文字,文字会自动调整间距,使左右两端对齐</div>
</body>
</html>

实际应用

场景1: 标题居中

h1, h2, h3 {
  text-align: center;
}

场景2: 按钮居中

.button {
  text-align: center;
}

场景3: 图片居中

.container {
  text-align: center;
}

.container img {
  display: inline-block;
}

场景4: 文章正文两端对齐

.article p {
  text-align: justify;
  line-height: 1.8;
}

场景5: 表格对齐

/* 表头居中 */
th {
  text-align: center;
}

/* 左对齐列 */
td:first-child {
  text-align: left;
}

/* 数字右对齐 */
td:last-child {
  text-align: right;
}

注意事项

  1. 作用范围: 只对块级元素的行内内容生效
  2. 继承性: 会继承给子元素
  3. 行内元素: 对行内元素本身无效

学习要点

  1. 常用值: center(居中), left(左对齐,默认), right(右对齐)
  2. 作用: 对块级元素的行内内容(文字、图片等)对齐
  3. 继承: 会继承给子元素
  4. 应用: 标题居中、按钮居中、表格对齐