The Translate is a method Transform used to move elements.
It accepts two values representing the axes X
(horizontal) and the Y
(vertical).
The difference between translate
and margin-left
is only conceptual. While one moves the element, or another just applies a margin.
The advantage of translate
about the margin
is that it is much more efficient and flexible when positioning or moving an element.
For example:
With translate
I can center a div
regardless of its width:
div{
width: 100px;
height: 100px;
background: red;
position: relative;
left: 50%;
transform: translate(-50%);
}
<div>
foo
</div>
Already with margin-left
, to have the same result, I get "stuck" to the width of the div
, because to center I need to back half the width (-50px
):
div{
width: 100px;
height: 100px;
background: red;
left: 50%;
margin-left: -50px;
position: relative;
}
<div>
foo
</div>
That is, with translate
, no matter the width of the element it will always be centered, while with margin-left
, i need to know the width of the element and put a fixed value (half).
What do you mean? It depends on the scope of how you will use.... talking only so it is difficult to give you an answer. In your block2 for example to center horizontally, simply remove the
position:absolute
and putmargin: auto
that it stays in the center.... Explain better what you need.– hugocsl
want to know the best way to position an element in the center responsibly
– Hudson Holanda
In this case Transform:Translate can be better pq facilitates to center both vertically and horizontally, independent of the width and height of the elements. Using margin vc may need "perfect numbers" to find optimal distances and even then may not be 100% responsive depending on the screen. But every case is a case
– hugocsl