CSS:在页面中间放置文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7948333/
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-30 02:02:25  来源:igfitidea点击:

CSS: Position text in the middle of the page

csstextpositioning

提问by snarkyazoid

I would like to position a <h1>in the middle of any user's page. I have been searching the internet and they all position it in the incorrect place. Thank you!

UPDATE: I mean vertical and horizontal! In the exact middle!
ALSO: There is nothingelse on the page.

我想将 a<h1>放在任何用户页面的中间。我一直在网上搜索,他们都把它放在了不正确的地方。谢谢!

更新:我的意思是垂直和水平!正好在中间!
另外:页面上没有其他内容。

回答by Ry-

Try this CSS:

试试这个 CSS:

h1 {
    left: 0;
    line-height: 200px;
    margin-top: -100px;
    position: absolute;
    text-align: center;
    top: 50%;
    width: 100%;
}

jsFiddle: http://jsfiddle.net/wprw3/

jsFiddle:http: //jsfiddle.net/wprw3/

回答by claytronicon

Here's a method using display:flex:

这是一种使用方法display:flex

.container {
  height: 100%;
  width: 100%;
  display: flex;
  position: fixed;
  align-items: center;
  justify-content: center;
}
<div class="container">
  <div>centered text!</div>
</div>

View on Codepen
Check Browser Compatability

查看 Codepen
检查浏览器兼容性

回答by Purag

Even though you've accepted an answer, I want to post this method. I use jQuery to center it vertically instead of css (although both of these methods work). Hereis a fiddle, and I'll post the code here anyways.

即使您已经接受了答案,我还是想发布此方法。我使用 jQuery 将其垂直居中而不是 css(尽管这两种方法都有效)。是一个小提琴,无论如何我都会在这里发布代码。

HTML:

HTML:

<h1>Hello world!</h1>

Javascript (jQuery):

Javascript (jQuery):

$(document).ready(function(){
  $('h1').css({ 'width':'100%', 'text-align':'center' });
  var h1 = $('h1').height();
  var h = h1/2;
  var w1 = $(window).height();
  var w = w1/2;
  var m = w - h
  $('h1').css("margin-top",m + "px")
});

This takes the height of the viewport, divides it by two, subtracts half the height of the h1, and sets that number to the margin-topof the h1. The beauty of this method is that it works on multiple-line h1s.

这将获取视口的高度,将其除以 2,减去 h1 高度的一半,并将该数字设置为 h1 的高度margin-top。这种方法的美妙之处在于它适用于多行h1

EDIT:I modified it so that it centered it every time the window is resized.

编辑:我修改了它,以便每次调整窗口大小时都将其居中。