Left and Translate

Asked

Viewed 52 times

0

I recently saw that some programmers are using left and translate, instead of left and margin.

Example below

.container{
width 100%;
border: 1px solid black;
height:300px;
}
.bloco1{
width:50px;
height:50px;
background-color:red;
position:absolute;
left:50%;
transform:translate(-50%, 50%);

}
.bloco2{
width:50px;
height:50px;
background-color:red;
position:absolute;
top:35%;
left:50%;
margin-left:-5%;

}
<div class="container">
<div class="bloco1"></div>
<div class="bloco2"></div>
</div>
What is the difference between the two, which is the best and most efficient?

  • 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 put margin: auto that it stays in the center.... Explain better what you need.

  • want to know the best way to position an element in the center responsibly

  • 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

1 answer

0

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).

  • Thanks Bro, thanks there. So the best is to use Translate is not practical, fast and efficient?

  • In certain cases yes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.