HexMania Hexy
HexMania Hexy

Reputation: 35

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

I'm trying to do the simple task of moving a div up and down to give a floating/hovering effect using bottom instead of top.

I'm 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:

.Mail {
  margin-top: -77px;
  margin-left: 791px;
  animation: MoveUpDown 1s linear infinite;
}

@keyframes MoveUpDown {
  0%, 100% {
    bottom: 0;
  }
  50% {
    bottom: 20px;
  }
}
<link href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" rel="stylesheet">

<i class="Mail fas fa-envelope"></i>

Upvotes: 2

Views: 5161

Answers (3)

Hamza Dahmoun
Hamza Dahmoun

Reputation: 1294

For anyone else who's looking for the same thing, here is a simpler answer using transform: translateY();:

.moving-div{
margin-top:100px;
    animation-name: move;
    animation-duration: 1s;
    animation-iteration-count: infinite;
    animation-direction: alternate;
}

@keyframes move {
    0% {
        transform: translateY(25%);
    }

    100% {
        transform: translateY(-25%);
    }
}
<div class="moving-div">
I am moving up and down
</div>

Upvotes: 0

Elharony
Elharony

Reputation: 981

bottom, top, right, left need a position property. The default position value is static which has no effect as MDN Explained here. I highly recommend reading the bottom guide to see its effect with different position values!

Anyways, your animation code is correct. However, you need to understand how the position property work in CSS to avoid similar mistakes.

P.S: Start by understanding the following: relative absolute fixed, here is a great resource from MDN Web Docs about Positioning

Upvotes: 1

VXp
VXp

Reputation: 12068

You need to set its position to absolute in order for the bottom property to take effect:

.Mail {
  margin-top: -77px;
  margin-left: 791px;
  position: absolute;
  bottom: 0;
  animation: MoveUpDown 1s linear infinite;
}

@keyframes MoveUpDown {
  50% {bottom: 20px}
}
<link href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" rel="stylesheet">

<i class="Mail fas fa-envelope"></i>

Upvotes: 1

Related Questions