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
center h1 in the middle of screen
提问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-height
property specifies the line height (which centres it vertically), and the text-align:center
place 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: fixed
you set the position to a fixed value, and with top
and left
both set to 50%
you'll get it in the middle of the screen.
随着position: fixed
你设置的位置为固定值,与top
和left
均设定为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>