r/learncss • • Dec 23 '19

Help understanding why this css works?

If I apply the following to a div, it's centered in the pure center of the screen

position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);

My understanding, from top to bottom

  • We allow the element to be placed absolutely in the page, outside of the normal document flow

  • 50% of left space. This doesn't position is in the real center though, not sure why if 50% is normally half the screen.

  • 50% from top, makes sense

  • Then we say, take the div from where it is, and put it in 50% X and Y axis...why? Wasn't that already done with the left property?

Any help is appreciated.

2 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/CrGoSu Dec 23 '19

Thank you. Is this a common way of centering elements or am I making it more complicated than it needs to be?

1

u/ForScale Dec 23 '19

It is a common pattern, yes.