As mention above:
position:relative
and translate
can achieve the same effect in a different way
position:relative
happen in the layout phase which means it can interact with other elements in terms of layout
while translate
happens when all the layout process complete, further it even already painted, what is remaining is a matter where to put the element, so it has no interaction with the existing layout
consider the following example which will present an obvious visual difference by using the two methods
.container {
width: 300px;
height: 300px;
overflow: scroll;
background: red;
}
.child {
width: 280px;
height: 280px;
background: green;
}
<div class="container">
<div class="child"></div>
</div>
By setting position:relative;top:100px
to the child element, the container has no enough space to hold the child, and because of the fact that overflow
is set as scroll
, the scroll bar will present
On the other hand, By setting transform:translateY(100px)
, it has nothing to do with the layout, so the scrollbar will not present
Like the spec said:
However, if relative positioning causes an 'overflow:auto' or
'overflow:scroll' box to have overflow, the UA must allow the user to
access this content (at its offset position), which, through the
creation of scrollbars, may affect layout
To conclude, position
is involved in layout, while transform
not, which means transform
can have better performance.
prefer transform
to position
when the layout is not your concern