Mohmmad Ebrahimi Aval
Mohmmad Ebrahimi Aval

Reputation: 482

how to change element CSS position with animation

I want to change an HTML element position from static to fixed at top 50% and left 50% of the browser window but the code just leads to background-color change!

div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: static;
    top: auto;
    left: auto;
    animation-name: example;
    animation-duration: 4s;
}

@keyframes example {
    from {
        background-color: red;
        position: static;
        top: auto;
        left: auto;
    }
    to {
      background-color: yellow;
      position: fixed;
      top: 50%;
      left: 50%;
     }
}

Upvotes: 7

Views: 29416

Answers (4)

Mohmmad Ebrahimi Aval
Mohmmad Ebrahimi Aval

Reputation: 482

I found the answer via 'Vangel Tzo' help :

div {
    width: 100px;
    height: 100px;
    background-color: red;
    animation-name: example;
    animation-duration: 4s;
}

@keyframes example {
    from {
        background-color: red;
    }
    to {
      background-color: yellow;
      transform: translate(50vw, 50vh);
     }
}

Upvotes: 2

wikijames
wikijames

Reputation: 192

You can't change css position value with css animation.

You can do this with jQuery

example is with hover, you can do according to your choice.

Jquery

With the use of "Css"

$(".div_name").hover(function(){
    $(this).css("position", "static");
    }, function(){
    $(this).css("position", "fixed");
});

With the use of "Animate"

 $(".div_name").hover(function(){
        $(this).animate({"position":"static"}, 1000);
        }, function(){
        $(this).animate({"position":"fixed"}, 1000);
    });

Upvotes: 0

Vangel Tzo
Vangel Tzo

Reputation: 9313

Short answer: You can't animate position.

Instead of applying position: fixed through keyframes try to add a class fixed or something via javascript.

An example: https://jsfiddle.net/6Ldqhoce/

Alternative you could move the element with transform: translate but it won't be fixed.

Upvotes: 6

Shrinivas Shukla
Shrinivas Shukla

Reputation: 4453

You cannot change position using CSS-animation because position is NOT an animatable property.

List of animatable properties.

However, this fiddle might help you.

Upvotes: 4

Related Questions