Why is translateY(-50%) needed to center an element which is at top: 50%?

top:0 (default)

By default, your element is at the top of the page, and the top of the element is at 0:

--------Top of Page--------
{element}


------Middle of  Page------



------Bottom of  Page------

top:50%

When you move it down by 50% height (50% of the entire page), the top of the element is at the 50% mark, meaning the element starts at 50% and is not centered.

--------Top of Page--------



------Middle of  Page------
{element}


------Bottom of  Page------

top:50%; transform:translateY(-50%);

When the top of the element is at the halfway mark, we can move the element back up by half of its own height to center it with the whole page. That’s exactly what transform:translateY(-50%); does:

--------Top of Page--------



{element}-Middle of Page---



------Bottom of  Page------

But why can’t we just say top: 25% or something like that? I’ve made a quick snippet to show you the difference with that implementation:

body {
  margin: 0;
}
.row {
  display: flex;
  justify-content: space-between;
}
.container {
  display: inline-block;
  margin: 5px;
  width: 200px;
  height: 200px;
  background: tomato;
}
.inner {
  position: relative;
  margin: 0 auto;
  height: 50%;
  width: 50%;
  background: #FFC4BA;
}
.inner.small {
  width: 25%;
  height: 25%;
}
.inner.big {
  width: 75%;
  height: 75%;
}
.percent {
  top: 25%
}
.transform {
  top: 50%;
  transform: translateY(-50%);
}
<b>First row </b>looks alright, but that's because the gap works well with the 25%
<div class="row">
  <div class="container">
    <div class="inner percent"></div>
  </div>
  <div class="container">
    <div class="inner transform"></div>
  </div>
</div>
<b>Second row </b>made the center square a bit smaller, and the 25% now is too high as we'd expect the bottom of the element to reach 75%
<div class="row">
  <div class="container">
    <div class="small inner percent"></div>
  </div>
  <div class="container">
    <div class="small inner transform"></div>
  </div>
</div>
<b>Third row </b>now I've made the center box big and it ends lower than 75% making 25% start too late
<div class="row">
  <div class="container">
    <div class="big inner percent"></div>
  </div>
  <div class="container">
    <div class="big inner transform"></div>
  </div>
</div>

Leave a Comment