Need some explanation for transform: translate();

Hello everyone. I am working on the survey form project and I wanted some help. I wanted to add a blurred background image behind the form before starting to add things and found a way to do it after a while.

Where I get stuck is that in order to add text etc. above the image, you have to use position: absolute and I set the top and left to 50% but it didn’t center it. So then I found out about transform: translate and just adding transform: translate (-50%, -50%) in addition to top and left 50% centered it.

Can someone explain why that happened? Why didn’t it center it with just top and left at 50% and what exactly did transform do?

Here is the pen if anyone can check it out and give me an explanation I’d be grateful.

Hello @marios96,
If you set top:50%,left:50% , your text will not be centered . It will start from the middle of the screen ( a point centered in the middle) and then you have to count the space taken from all the text.
If you use translate(-50%,-50%) , you will take 50% of the text size and move it to be centered.
I.e. if you have an image of size (300px,300px) and you want to put in the center of the screen.
If you set top:50% , left:50%, the image will start from the point in the middle of the screen and occupies 300px from the center to the right border of the screen and 300px to the bottom of the screen.
But if you use translate (-50%,-50%), -50% = 150px; Now you will move the image 150px left and 150px up, so it will be positioned with the center of the image corresponding to the center of the screen.
I hope it was clear :confused:

1 Like

Because the top/left 50% is calculated from the edge of the parent element to the edge of the element you’re applying it to. Whereas the translation is applied on the element itself

1 Like

Both of the previous answers should help you, but if you’re a visual person like me and need to see what’s going on take a look at the " Using Position and Transform property" section in this article.

https://medium.com/front-end-weekly/absolute-centering-in-css-ea3a9d0ad72e#:~:text=Absolute%20Center%20using%20translate&text=If%20you%20want%20to%20center,when%20working%20with%20block%20element).

1 Like

Thank you everyone, I understand it a lot better now. Seems like positioning gets more complicated as I dive more into it but I’m having fun so far. Thanks again.