Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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%;
     }
}
like image 500
Mohmmad Ebrahimi Aval Avatar asked Aug 05 '15 06:08

Mohmmad Ebrahimi Aval


People also ask

How to set transition animation in CSS?

You can use CSS property transition to smoothly move, change size, change position, change color or other attribute of HTML element. To set an animation, you have to include the transition property into the specific style and set the attributes.

How to change CSS position value with CSS animation?

You can't change css position value with css animation. example is with hover, you can do according to your choice. i khow how to do it with jQuery but i want use CSS.

What is CSS animation?

CSS allows animation of HTML elements without using JavaScript or Flash! The numbers in the table specify the first browser version that fully supports the property. What are CSS Animations? An animation lets an element gradually change from one style to another.

How to animate the position of an element?

Short answer: You can't animate position. Instead of applying position: fixed through keyframes try to add a class fixed or something via javascript. Alternative you could move the element with transform: translate but it won't be fixed. how set {transform: translate} by percentage for browser dimention ?


Video Answer


2 Answers

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.

like image 149
Vangel Tzo Avatar answered Nov 08 '22 05:11

Vangel Tzo


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);
     }
}
like image 24
Mohmmad Ebrahimi Aval Avatar answered Nov 08 '22 04:11

Mohmmad Ebrahimi Aval