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 nothing else on the page.
Try this CSS:
h1 {
left: 0;
line-height: 200px;
margin-top: -100px;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
}
jsFiddle: http://jsfiddle.net/wprw3/
Here's a method using 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>
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). Here is a fiddle, and I'll post the code here anyways.
HTML:
<h1>Hello world!</h1>
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-top
of the h1. The beauty of this method is that it works on multiple-line h1
s.
EDIT: I modified it so that it centered it every time the window is resized.
来源:https://stackoverflow.com/questions/7948333/css-position-text-in-the-middle-of-the-page