Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

translate() vs top/left for positioning

From what I find, translate() seems to offer smoother animations over plain top/left but my question is related to a CSS layout I saw recently. The author used the following setting to position a block of text inside the main header image:

.hero-text-box {
    position: absolute;
    width: 1140px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

He didn't explain, and I'm left wondering what advantage translate() has over top/left in percentage values when it comes to pure layouts (i.e., no animation). I'm guessing this really doesn't matter in the case of layouts, and was the result of the author's habits. But even then, this combines both top/left and translate(). What's going on?

like image 537
ankush981 Avatar asked Jan 31 '26 10:01

ankush981


1 Answers

The code you posted is used to position an element vertically and horizontally centered. translate is used here because the percentage are relative to the element dimensions. The percentage values for top and left with position: absolute are relative to the dimensions of the first parent element with position set to relative, absolute or fixed.

like image 64
cyr_x Avatar answered Feb 03 '26 02:02

cyr_x