Left and Translate

0

Recently I 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 the most efficient?     
asked by anonymous 27.02.2018 / 14:57

1 answer

0

translate is a method transform used to move elements.

It accepts two values that represent the axes X (horizontal) and 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 over margin is that it is much more efficient and flexible when you want to position or move an element.

For example:

With translate I can centralize a div regardless of its width:

div{
   width: 100px;
   height: 100px;
   background: red;
   position: relative;
   left: 50%;
   transform: translate(-50%);
}
<div>
   foo
</div>

Now with margin-left , to have the same result, I get stuck to the width of div , because to center I need to go 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 , it does not matter what element width it will always be centered on, while with margin-left , I need to know the width of the element and put a fixed value (half). >     

27.02.2018 / 15:41