Skip to content

CSS 对齐

「对齐」在不同场景指不同事:文字在块内的对齐、块级元素在容器内的居中、Flex/Grid 子项的对齐等。本节按场景说明常用写法。

一、文本水平对齐:text-align

只影响块级元素内部行内内容(文字、行内图片等)的水平对齐。

css
p {
  text-align: left;    /* 左对齐(默认) */
  text-align: center;  /* 居中 */
  text-align: right;   /* 右对齐 */
  text-align: justify; /* 两端对齐 */
}

二、块级元素在容器内水平居中

给块级元素设固定宽度,左右 margin 设为 auto

css
.container {
  width: 600px;
  margin-left: auto;
  margin-right: auto;
  /* 或 */
  margin: 0 auto;
}

三、单行文本垂直居中(行高法)

若容器高度固定,希望单行文字垂直居中,可设 line-height 等于容器高度:

css
.box {
  height: 60px;
  line-height: 60px;
}

多行文本不适合用此法。


四、Flex 对齐(推荐用于多元素居中、分布)

父元素 display: flex,用以下属性控制子项对齐:

  • justify-content:主轴(默认横向)方向上的分布
    • center:居中
    • space-between:两端对齐、中间均分
    • space-around / space-evenly:间隔分布
  • align-items:交叉轴(默认纵向)方向上的对齐
    • center:垂直居中
    • flex-start / flex-end:起点/终点对齐
css
.center-box {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

这样可同时实现水平+垂直居中(子项可以是块或文字)。


五、Grid 对齐

display: grid 的容器上:

  • justify-items / align-items:单元格内内容对齐
  • justify-content / align-content:整个网格在容器内的对齐(当网格总尺寸小于容器时)
  • 子项上可用 justify-self / align-self 单独覆盖

六、绝对定位 + 偏移实现居中(传统写法)

子元素 position: absolute,父元素 position: relative,子元素设:

css
.child {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

通过 left/top 50% 再反向平移自身宽高的一半,实现居中。Flex 普及后此法用得较少。


小结

  • 文字水平对齐:在块上设 text-align
  • 块水平居中:定宽 + margin: 0 auto
  • 单行文字垂直居中line-height 等于容器高度。
  • 多元素、水平+垂直居中:用 Flexjustify-contentalign-items: center 最方便。
  • Grid 用 justify/align-items、content、self 等做更复杂对齐。

下一节学习 CSS 组合选择符