CSS move element by position or by transform?

14,045

Solution 1

If you want it animated, move it using transform:

dialog.style.transform = "translateY(100px)";
#dialog {transform: translateY(50px); transition: all 2s;}
<div id="dialog">Hello</div>

Also read Why Moving Elements With Translate() Is Better Than Pos:abs Top/left.

Solution 2

"Better", v1

My first thought on what "better" meant in this context is which one is more appropriate to use under different circumstances. Which leads me to say: "don't confuse positioning with design-y motion."

Case in point. You have a button. You want to apply an effect to that button so that in it's :active state it nudges down 2 pixels to mimic a "pushed" effect. That is a design-y motion that should be done with translate(). You could do it with top or bottom and relative positioning, but then you are confusing the concepts of positioning and design-y motion.

Let's say somewhere else in the app you absolutely position a button (perfectly legit). Now when that top: 2px; gets applied to the button in it's :active state, that button will likely go zooming off someplace you didn't expect, possibly making the button unclickable.

Using translate() will always "nudge" the element from it's current position which is perfect for an effect like this, or really any design-specific motion."Chris Coyier at A Tale of Animation Performance

Read this article please, it will provide you with all what you want to know about that topic. https://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/

Share:
14,045
NickC
Author by

NickC

Updated on July 23, 2022

Comments

  • NickC
    NickC almost 2 years

    Show I use absolute position or transform to move a <div> around the page?

    I seem to recall reading that moving objects using position such as:

    dialog.style.bottom = "100px";
    

    is slower and it is preferable to use transform to move the object instead:

    dialog.style.transform = "translateY(100px);
    

    However as I also have a CSS transition in place:

    transition: 2s
    

    does that make any difference, is transform still preferred over position or are they both the same now?

    • Ashok kumar
      Ashok kumar over 7 years
    • NickC
      NickC over 7 years
      The actual question seems to have got a bit lost in the various replies. The crux of it is whether position with a transition is any different to a transform? I understand the differences between a straight position vs transform but what about a position with transition?
  • Jonas Grumann
    Jonas Grumann over 7 years
    Yes, but why? Should have explained that, anyway, here it is: paulirish.com/2012/…
  • NickC
    NickC over 7 years
    I get the feeling it seems to be a matter of opinion then, no definitive answer to the basic question.