简体   繁体   中英

CSS move element by position or by transform?

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?

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 .

"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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM