Creating css transitions without using position:absolute

烂漫一生 提交于 2020-01-14 09:52:08

问题


I realize that css animations are a well covered topic, but I'm just wondering about the best way to create simple slide like transitions? Mostly, when you read about slide transitions like that, some kind of position:absolute is assumed. That is not the way content is usually organized in HTML and it shouldn't be.

So, if I want to create a transition of one div sliding to the left and one div sliding from the right, what would be a good strategy without assuming that any of those divs has absolute positioning or any other specific transition specific stuff going on to start with?

 <div class="container">
     <div class="this-should-slide-left">
         <div>Some content</div>
         <div>Some more</div>
     </div>
     <div class="this-should-from-left"><!--not visible initially-->
         <div>Some more content</div>
     </div>
 </div>

I came up with this solution which seems to work, even though I'm not sure if it's elegant:

http://jsfiddle.net/CAg4f/4/


回答1:


The best way to move elements around when animating is translating using css transforms.
For example, to transition when hovering over the container:

.this-should-slide-left,
.this-should-from-left {
    transition: transform .25s
}

.container .this-should-from-left {
    transform: translateX(100px);
}

.container:hover  .this-should-from-left {
    transform: translateX(0);
}

.container:hover .this-should-slide-left {
    transform: translateX(-100px);
}

Translating makes the transition much smoother as it takes advantage of hardware acceleration plus there is no positioning involved, so you have complete separation between the design of the layout and the design of the animation itself.

Read more here




回答2:


Aside from absolute positioning, there is relative positioning and margins.

While I would usually go with margins to manipulate a transition, relative positioning is probably the safest, as it will work for inline elements which can't necessarily be manipulated by margins.



来源:https://stackoverflow.com/questions/20293945/creating-css-transitions-without-using-positionabsolute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!