📜  如何在 div 中将文本设置为中间 - CSS (1)

📅  最后修改于: 2023-12-03 15:08:36.022000             🧑  作者: Mango

如何在 div 中将文本设置为中间 - CSS

在实现网页布局时,我们有时需要将文本设置在 div 中垂直和水平居中。本文将介绍几种在 div 中将文本设置为中间的方法。

方法一:使用display和text-align属性

我们可以将 div 的 display 属性设置为 table,然后将 div 中的文本的 text-align 属性设置为 center。

div {
  display: table;
}
div p {
  text-align: center;
}
方法二:使用display和margin属性

我们可以将 div 的 display 属性设置为 flex,然后将文本的 margin 属性设置为 auto。

div {
  display: flex;
  justify-content: center;
  align-items: center;
}
div p {
  margin: auto;
}
方法三:使用position和transform属性

我们可以将 div 的 position 属性设置为 relative,然后将文本的 position 属性设置为 absolute,并且使用 transform 属性将文本居中。

div {
  position: relative;
}
div p {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

以上三种方法均可以实现在 div 中将文本设置为中间,具体的使用方法可以根据具体的情况进行选择。