0

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)

Community
  • 1
  • 1
Guilherme Salomé
  • 1,899
  • 4
  • 19
  • 39

1 Answers1

0

According to my understanding, translateX() works the same as if you had used left (or right) to change the horizontal position of the element. The only difference is that when you use left to change the position, the element shifts accordingly and affects nearby elements. But if you use translateX the DOM is unaware of the transformation and renders all the nearby elements as if the transformed div was not moved at all. So if you do not want the position of neighboring elements to be affected by the change in the position of a particular div use translate.

The 50% refers to 50% of the width (when using translateX).

Anubhav
  • 7,138
  • 5
  • 21
  • 33