ankush981
ankush981

Reputation: 5417

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?

Upvotes: 3

Views: 5502

Answers (1)

cyr_x
cyr_x

Reputation: 14257

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.

Upvotes: 11

Related Questions