在屏幕中央将标题居中显示

32
如何水平垂直居中文本?我不想使用绝对定位,因为我试过了,我的其他div变得更糟了。还有其他方法可以做到吗?

div {
    height: 400px;
    width: 800px;
    background: red;
}
<div>
    <h1>This is title</h1>
</div>
    


您想让h1div中居中,还是让div在视口/屏幕中居中?请澄清。 - Marc Audet
4个回答

20

你可以使用display:flex,它为所有直接子元素创建了一个flex上下文,并且通过设置flex-direction属性来定义主轴方向,从而确定了flex容器中flex项目的放置方向。

div{
  height: 400px;
  width: 800px;
  background: red;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

2
希望 OP 不需要支持 Internet Explorer。 - John Dvorak
1
IE 10/11对于flexbox的支持还是不错的。 - Paulie_D

5

只需执行此操作,可适用于所有浏览器:

div{
     height: 400px;
     width: 800px;
     background: red;
     line-height: 400px;
     text-align: center;
}

line-height属性指定了行高(使其在垂直方向上居中),text-align:center使文本在水平方向上直接居中。


它也适用于div吗?因为我把它放在我的网站上,但它没有起作用。 - Dina
2
@Dina div是块级元素,所以不行。如果你想在div上使用它,请将div样式设置为display:inline。你应该使用span来处理内联文本。 - Mmm Donuts

1

-1

.container {
    display: table;
}
.centered {
    display: table-cell;
      height: 400px;
      width: 800px;
      background: red;
    text-align: center;
    vertical-align: middle;
    }
<div class="container">
<div class="centered">
  <h1>This is title</h1>
</div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接