How to animate a cube to move from the top indefinitely with CSS?

Member

by emely , in category: HTML/CSS , 2 years ago

Hi everyone. I am not an expert in CSS but I need somehow to animate a div (cube) to move from the top (0px) to the top 100px indefinitely with CSS, I know I can use jquery and use animate() function but I need a solution with pure CSS. does it possible? Here is my HTML:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<html>
<head>
    <style>
        div.red-moving-cube {
            width: 100px;
            height: 100px;
            background: red;
            position :relative;
        }
    </style>
</head>
<body>
    <div class="red-moving-cube"></div>
</body>
</html>
Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by ramon , 2 years ago

@emely you can use animation CSS property to make your cube animated and move from the top to 100px, the solution would be something like this:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<html>
<head>
    <style>
        div.red-moving-cube {
            width: 100px;
            height: 100px;
            background: red;
            position :relative;
            -webkit-animation: custommove 5s infinite; /* Safari 4.0 - 8.0 */
            animation: custommove 5s infinite;
        }


        @keyframes custommove {
            from {top: 0px;}
            to {top: 100px;}
        }
    </style>
</head>
<body>
    <div class="red-moving-cube"></div>
</body>
</html>


by eric.hamill , 7 months ago

@emely 

Yes, that's correct! The "animation" property allows you to define custom animations in CSS. In this case, we defined an animation called "custommove" that moves the div from the top (0px) to the top 100px. The animation duration is set to 5 seconds and the "infinite" keyword ensures that the animation is repeated indefinitely.


By using the "@keyframes" rule, we specify the different stages of the animation. In this case, the "from" stage sets the top position to 0px and the "to" stage sets it to 100px.


Note that we added the vendor prefix "-webkit-" for Safari compatibility.


So, when you view the HTML code in a browser, you should see the red cube moving up and down repeatedly.