Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS3 animation, translate to position

I have a div that I click on to drag it. Once it's on an area, it animates to its position via:

$("#wheel1").animate({left: "200px", top: "100px"});

I can also get it to animate with:

@-webkit-keyframes wheel1 {
    0% {
    }
    100% {
        -webkit-transform: translate(200px, 100px);
    }
}

The difference being; with jQuery it animates to 200px from the left of the document. With CSS3, it animates 200px from where you drop it (which is bad)

Is there a way to make CSS3 animate from the top left of the document, as jQuery does? I've tried changing transform-origin and a few other settings with no luck.

like image 335
Phill Avatar asked Jun 14 '12 01:06

Phill


People also ask

Can position be animated CSS?

Any CSS property that be transitioned can also be animated. Use animation-delay to pause before executing an animation, using the same time values as for duration. The animation-iteration-count property sets the number of times the animation plays, either as an integer or infinite.

Can you animate transform CSS?

Animating your Transforms If you think that's cool, realise that CSS Animation can be applied not just to the transforms, but also to other CSS properties including: opacity, colour and a bunch of others.

What are the advantages of using Translate () instead of absolute position?

Using 2D transforms instead of absolute positioning will typically provide better FPS by way of smaller paint times and smoother animation.

How do you translate y in CSS?

The CSS translateY() function is used to move elements in a two-dimensional space along the y -axis (vertically). It moves the position of the element on the vertical plane by the amount provided by t .


1 Answers

I'm not an expert in CSS3 transforms, but I think translate is relative to the element's original position.

One way I can see to achieve what you want with CSS would be to position the element absolutely, and use a CSS3 transition to change its left and top properties.

Here is a Fiddle: http://jsfiddle.net/nSa9s/2/

HTML:

<div class="box"></div>

CSS:

.box {
    position: absolute;
    background: #ff0000;
    left: 400px;
    top: 200px;
    width: 100px;
    height: 100px;
    -webkit-transition: all 1.0s linear;
    -moz-transition: all 1.0s linear;
    -o-transition: all 1.0s linear;
    -ms-transition: all 1.0s linear;    
    transition: all 1.0s linear;
}
.box.move {
    left: 200px;
    top: 100px;
}

jQuery:

$(document).ready(function() {
    $('.box').on('click', function() {
        $(this).addClass('move');
    });
});

The purpose of the JS is to add the move class to the element when it is clicked.

like image 93
Jonathan Nicol Avatar answered Oct 17 '22 05:10

Jonathan Nicol