【问题标题】:center h1 in the middle of screen [duplicate]在屏幕中间居中 h1 [重复]
【发布时间】:2016-04-07 10:35:25
【问题描述】:

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

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

【问题讨论】:

  • 您希望h1div 中居中还是div 在视口/屏幕中居中?请澄清,

标签: html css text-align


【解决方案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>

【讨论】:

    【解决方案2】:
    <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】:

      只需这样做,它适用于所有浏览器:

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

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

      【讨论】:

      • 它也适用于 div 吗?因为我把它放在我的网站上它没有用
      • @Dina div 是块元素,所以不是。如果您希望它在 div 上工作,请将 div 样式设置为 display: inline。您应该使用 span 来表示内联文本。
      【解决方案4】:

      您可以使用 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;
      }
      

      【讨论】:

      • 希望 OP 不需要支持 Internet Explorer。
      • IE 10/11 非常适合 flexbox。
      猜你喜欢
      • 2019-05-16
      • 1970-01-01
      • 2020-04-14
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      相关资源
      最近更新 更多