-1

I know different versions of this question have been asked a million times, but I can't seem to find a clear cut answer to my question. How do I vertically and horizontally center an h1 in the body of my document? I don't have it in another div or anything, I just want it centered on the page

Alex
  • 402
  • 5
  • 13

2 Answers2

0

You could add the CSS attribute text-align: center; To place it in the vertical center of the screen you need a workaround. Add

margin-top: calc(50vh - 12px);

calc does calculate what's in the brackets. vh is a measurement unit an means viewport height (in percent).

So basically you add an offset of 50% of the window height minus 12px (half of the text height when h1 is 24px) to the element

Karkan
  • 126
  • 2
  • 9
  • If the `h1` Element is not the only one in your site at this moment, you could also work with `position: absolute;` to avoid moving other elements. Then use `z-index: 99999;` (high number) to place the `h1` in the front to avoid it being overlayed by other elements. – Karkan Nov 09 '15 at 08:46
0

There are other options. Just for fun, here's one, although not the best option (I'd use display: table or flex). You don't have to use the containing element, but it's safer to do so than to put the header styles on the body element.

header {
  background: #30353b;
  position: relative;
  height: 100vh;
}

h1 {
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform:translate(-50%, -50%);
  -moz-transform:translate(-50%, -50%);
  -ms-transform:translate(-50%, -50%);
  -o-transform:translate(-50%, -50%);
  transform:translate(-50%, -50%);
  margin: 0;
  line-height: 0;
  color: white;
}

body {margin: 0; padding: 0;}
<header>
<h1>heading text</h1>
</header>
ralph.m
  • 13,468
  • 3
  • 23
  • 30