How to reposition a CSS element with animation

I want to change the position of an HTML element from static to fixed at 50% and keep 50% of the browser window, but the code just causes the background color to 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%;
     }
}

      

+3


source to share


4 answers


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);
     }
}

      

+1


source


The short answer is: You can't animate position.

Instead of applying position: fixed

through keyframes, try adding a class fixed

or something through javascript.



Example: https://jsfiddle.net/6Ldqhoce/

Alternatively, you can move the element with transform: translate

, but it won't fix it.

+1


source


You cannot change position

with help CSS-animation

because position

NOT an animated property...

List of animation properties .

However, this script can help you.

+1


source


You cannot change the css position value with css animation.

You can do it with jQuery

freeze example, you can do as you choose.

JQuery

With "Css"

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

      

Using "Animation"

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

      

0


source







All Articles