0

I have a login box on my page which I want to put in the middle of the page, so I used:

.login {
  width: 280px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}

And it worked. However, I'm not sure why. From my understanding, the top and left 50% puts the box left top corner in the middle, so the center of the box itself isn't in the center yet, but then after the transform translate line, it puts the box in the middle, how?

I thought that translate would just translate 50% x axis back and 50% y axis back to original position.

Hello World
  • 191
  • 2
  • 9
  • 2
    Normally the origin point is the upper left corner of an element. The transform moves it to the center> one example I randomly Googled: https://medium.com/front-end-weekly/absolute-centering-in-css-ea3a9d0ad72e – j08691 Jul 13 '20 at 01:46
  • 1
    `top: 50%; left: 50%;` -- the 50% is relative to the size of the container. `transform: translate(-50%,-50%);` -- the 50% is relative to the size of the element itself. So you move it right/down by 50% of the container, then left/up by 50% of the element, thus centering it. This fails badly if the element is bigger than the device's screen, which can easily happen on mobile. – Niet the Dark Absol Jul 13 '20 at 01:52
  • 1
    `top` and `left` are determined by the elements container. `transform` properties are based on the element, and not determined by the elements container. e.g. top and left move the element within the container, transform move the element based on its own width/height/depth. – disinfor Jul 13 '20 at 01:52

1 Answers1

11

When using position:absolute; you're positioning the element relative to its container. Let's say that in your example the container is the body of the page.

And the origin point of the positioning is the very top-left of the element (If the direction is set to ltr)

When using transform:translate() you translate the element relative to itself.

Try to remove the transform:translte() property and you will find that the element's top-left corner is in the center of the body.

enter image description here

image source: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

When you re-add the transform:translate(-50%,-50%); the element reposition its center to be at the place of the old top left corner, and here the center of the element will be at the center of the page.

enter image description here

image source: https://www.youtube.com/watch?v=KJFWsggjUcE

xTrimy
  • 804
  • 9
  • 23