Skip to content

css 所有居中方法

在 CSS 中,有多种方法可以使元素居中,这些方法适用于不同的情境和需求。以下是一些常见的居中方法及其示例:

1. 使用 text-align 居中文本

适用于块级元素中的内联内容或文本。

html
<div class="container">
  <p>这是一段居中的文本。</p>
</div>
css
.container {
  text-align: center;
}

2. 使用 margin 居中块级元素

适用于将一个块级元素在其父容器中水平居中。

html
<div class="container">
  <div class="centered-box">居中的块级元素</div>
</div>
css
.container {
  width: 100%;
}

.centered-box {
  width: 50%;
  margin: 0 auto;
}

3. 使用 flexbox 居中

适用于水平和垂直居中,非常灵活。

父元素水平和垂直居中子元素

html
<div class="container">
  <div class="centered-box">居中的元素</div>
</div>
css
.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;/* 垂直居中 */
  height: 100vh; 
}

4. 使用 grid 居中

同样适用于水平和垂直居中,非常简洁。

父元素水平和垂直居中子元素

html
<div class="container">
  <div class="centered-box">居中的元素</div>
</div>
css
.container {
  display: grid;
  place-items: center; /* 垂直和水平居中 */
  height: 100vh; 
}

5. 使用绝对定位和 transform

适用于已知元素尺寸的情况下的水平和垂直居中。

html
<div class="container">
  <div class="centered-box">居中的元素</div>
</div>
css
.container {
  position: relative;
  height: 100vh; /* 父容器高度 */
}

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

6. 使用 table 及其属性

虽然不是最推荐的方法,但在某些老旧代码中可能会见到。 [弃用]

html
<div class="container">
  <div class="wrapper">
    <div class="centered-box">居中的元素</div>
  </div>
</div>
css
.container {
  display: table;
  width: 100%;
  height: 100vh; /* 父容器高度 */
}

.wrapper {
  display: table-cell;
  text-align: center; /* 水平居中 */
  vertical-align: middle; /* 垂直居中 */
}

7. 使用行内块级元素和 vertical-align

适用于单行文本的垂直居中。

html
<div class="container">
  <span class="centered-text">居中的文本</span>
</div>
css
.container {
  height: 100vh; /* 父容器高度 */
  text-align: center; /* 水平居中 */
  line-height: 100vh; /* 利用行高垂直居中 */
}

.centered-text {
  display: inline-block;
  vertical-align: middle; /* 修正可能的基线对齐问题 */
  line-height: normal; /* 恢复正常的行高 */
}

8. 使用 writing-mode 和 text-align

适用于垂直方向的内容居中(如垂直文本)。

html
<div class="container">
  <div class="centered-text">垂直居中</div>
</div>
css
.container {
  height: 100vh; /* 父容器高度 */
  writing-mode: vertical-lr; /* 垂直书写模式 */
  text-align: center; /* 垂直方向居中 */
}

.centered-text {
  display: inline-block;
  /* 如果需要水平方向也居中,可以添加以下样式 */
  /* transform: rotate(90deg); */
}

总结

选择哪种居中方法取决于具体的需求和布局情境。flexbox 和 grid 是现代布局中最强大和灵活的工具,适用于大多数情况。绝对定位和 transform 适用于需要精确控制的位置的情况,而 text-align 和 margin 则适用于简单的文本和块级元素居中。

京ICP备2024093538号-1