How to move a div up and down infinitely in CSS3?

user3112634 picture user3112634 · Mar 14, 2016 · Viewed 70.5k times · Source

Hello I am trying to do the simple task of moving a div up and down to give a floating/hovering effect using bottom instead of top. So from bottom: 63px to bottom: 400px.

I am new to CSS and keyframes! As you can probably tell But here is what I have tried and it didn't seem to do anything:

.piece-open-space #emma {
    background-image: url('images/perso/Emma.png?1418918581');
    width: 244px;
    height: 299px;
    position: absolute;
    display: block;
    width: 244px;
    background-image: none;
    position: absolute;
    left: 2149px;
    bottom: 63px;
    -webkit-animation: MoveUpDown 50s linear infinite;
}

@-webkit-keyframes MoveUpDown {
    from {
        bottom: 63px;
    }
    to { 
        bottom: 400px;
    }
}

Update

The problem is it won't loop with is the goal I am looking for it gets to 400px then instantly goes back to 63px how would i make it get to 400px and then go back down to 63px it give the effect of an endless loop of "hovering/floating".

Answer

Stickers picture Stickers · Mar 14, 2016

You can adjust the timing of the @keyframes as follows:

.object {
  animation: MoveUpDown 1s linear infinite;
  position: absolute;
  left: 0;
  bottom: 0;
}

@keyframes MoveUpDown {
  0%, 100% {
    bottom: 0;
  }
  50% {
    bottom: 100px;
  }
}
<div class="object">
  hello world!
</div>

EDIT

As pointed out in a comment below using transform is preferred for high performance animations.

.object {
  animation: MoveUpDown 1s linear infinite;
  position: absolute;
  left: 0;
  bottom: 0;
}

@keyframes MoveUpDown {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-100px);
  }
}
<div class="object">
  hello world!
</div>