📜  如何在 css 中将文本输入居中(1)

📅  最后修改于: 2023-12-03 14:52:16.174000             🧑  作者: Mango

如何在 CSS 中将文本输入居中

在 CSS 中,有许多不同的方法可以将文本输入居中,下面将介绍其中几种。

水平居中
1. text-align 属性

使用 text-align: center 属性将文本内容水平居中。

.center {
  text-align: center;
}
2. display 和 margin 属性

使用 display: flex; 属性使容器成为 flex 容器,然后使用 margin: auto; 将子元素居中。

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="container">
  <p>你要居中的文本内容</p>
</div>
3. display 和 text-align 属性

使用 display: inline-block; 属性将文本内容变成块级元素,并使用 text-align: center; 属性将其水平居中。

.center {
  display: inline-block;
  text-align: center;
}
垂直居中
1. line-height 属性

通过设置行高大于等于容器高度,可以使文本内容垂直居中。

.container {
  height: 100px;
  line-height: 100px;
}
2. display 和 margin 属性

使用 display: flex; 属性使容器成为 flex 容器,然后使用 margin: auto; 将子元素居中。

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="container">
  <p>你要居中的文本内容</p>
</div>
3. position 和 transform 属性

使用 position: absolute; 将文本内容绝对定位到容器的中心,然后使用 transform: translate(-50%, -50%); 将其向左上角偏移50%,使其居中。

.container {
  position: relative;
}

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
结论

以上是几种常见的文本内容居中的方法,可以根据不同的场景和需要进行选择和使用。