0

I want to center the <div> horizontally and vertically, and the children <h1> and <h2> elements should be centered horizontally relative to the parent <div>, so I applied a class for that, shown below. It isn’t centered, but aligned left instead. What’s going on?

.centered {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.hcentered {
  left: 50%;
  transform: translate(-50%, 0);
}

.results {
  position: absolute;
}

.resultsText {
  position: relative;
}
<div class="centered results">
  <h1 class="hcentered resultsText">Header 1</h1>
  <h2 class="hcentered resultsText">Header 2</h2>
</div>
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
BrianZhang
  • 153
  • 1
  • 8

1 Answers1

2

h1 and h2 are block level elements so by default they are 100% wide. Instead of all of the complex calculation, simply use text-align: center;

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445