I was trying to find out how to dynamically center a text inside a div
box using only CSS3 and I found this topic: https://stackoverflow.com/a/25799339/1445572
I used the "Approach 1" and it solved my problem:
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
Now I am trying to understand why this code works. I know that when you change the position
to absolute
, you remove the element from the normal flow and you can position it (by using top
, left
, ...) in relation to its containing element.
Therefore, the code:
.container {
position: absolute;
top: 50%;
left: 50%;
}
positions the starting edge of text box right in the center of the div
. Even though the text box in the center, the text itself is not centered. So we need to compensate that somehow.
QUESTION: What is translateX(-50%)
doing exactly? More specifically, 50%
of what?
(I couldn't find an explanation of translateX
using percentages and their meaning in this context)