Html 在屏幕中间居中 h1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34580572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 18:43:08  来源:igfitidea点击:

center h1 in the middle of screen

htmlcsstext-align

提问by Dina

How can I center horizontally and vertically a text? I don't want to use position absolute because I try with it and my other div getting worse. Is there another way to do that ?

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

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

采纳答案by elreeda

you can use display flex it enables a flex context for all its direct children, and with flex direction establishes the main-axis, thus defining the direction flex items are placed in the flex container

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

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

回答by Kris

Just do this, which works on every browser:

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

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

The line-heightproperty specifies the line height (which centres it vertically), and the text-align:centerplace it directly in the centre horizontally.

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

回答by J_from_Holland

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

With position: fixedyou set the position to a fixed value, and with topand leftboth set to 50%you'll get it in the middle of the screen.

随着position: fixed你设置的位置为固定值,与topleft均设定为50%你会得到它在屏幕的中间。

Good luck coding!

祝你编码好运!

Here is some more information: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

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

回答by Steve Harris

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