中心h1在屏幕中间

时间:2016-01-03 19:17:54

标签: html css text-align

如何将文本水平和垂直居中?我不想使用绝对位置,因为我尝试使用它而我的其他div变得更糟。还有另一种方法吗?



div {
    height: 400px;
    width: 800px;
    background: red;
}

<div>
    <h1>This is title</h1>
</div>
    
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:10)

你可以使用display flex它为所有直接子项启用flex上下文,并且flex方向建立主轴,从而定义flex项放置在flex容器中的方向

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

答案 1 :(得分:4)

这样做,适用于每个浏览器:

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

line-height属性指定行高(垂直居中),text-align:center将其直接放置在水平中心。

答案 2 :(得分:0)

<div>
  <style>
div {
  position: fixed;
  top: 50%;
  left: 50%;
}</style>
<h1>This is title</h1>
</div>

使用position: fixed您将位置设置为固定值,并且topleft都设置为50%,您将获得它的中间位置屏幕。

祝你好运!

以下是一些更多信息:https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

答案 3 :(得分:0)

.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>

相关问题