Perform Animation on CSS margin-top

CSS margin-top animations allow you to create smooth transitions by changing an element's top margin over time. This is commonly used for creating sliding effects and dynamic spacing animations.

Syntax

@keyframes animation-name {
    from { margin-top: initial-value; }
    to { margin-top: final-value; }
}

selector {
    animation: animation-name duration timing-function iteration-count;
}

Example: Basic Margin-Top Animation

The following example demonstrates a smooth margin-top animation that moves an element down and back up −

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        height: 200px;
        background-color: #f0f0f0;
        padding: 20px;
        border: 2px solid #ddd;
    }
    
    .animated-box {
        width: 200px;
        height: 50px;
        background-color: #ff6b35;
        color: white;
        text-align: center;
        line-height: 50px;
        font-weight: bold;
        animation: slideDown 3s infinite;
        margin-top: 0;
    }
    
    @keyframes slideDown {
        0% { margin-top: 0px; }
        50% { margin-top: 100px; }
        100% { margin-top: 0px; }
    }
</style>
</head>
<body>
    <h2>Margin-Top Animation Demo</h2>
    <div class="container">
        <div class="animated-box">Moving Box</div>
    </div>
</body>
</html>
An orange box with white text "Moving Box" smoothly moves down 100px from the top and returns to its original position repeatedly within a gray container.

Example: Staggered Animation Effect

This example shows multiple elements with different animation delays to create a cascading effect −

<!DOCTYPE html>
<html>
<head>
<style>
    .box {
        width: 60px;
        height: 60px;
        background-color: #4CAF50;
        margin: 10px;
        display: inline-block;
        animation: bounce 2s infinite;
    }
    
    .box:nth-child(2) { animation-delay: 0.2s; }
    .box:nth-child(3) { animation-delay: 0.4s; }
    .box:nth-child(4) { animation-delay: 0.6s; }
    
    @keyframes bounce {
        0%, 100% { margin-top: 0px; }
        50% { margin-top: -30px; }
    }
</style>
</head>
<body>
    <h2>Staggered Bounce Effect</h2>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</body>
</html>
Four green squares bounce up and down in sequence, creating a wave-like staggered animation effect with each box starting slightly after the previous one.

Conclusion

Animating margin-top is an effective way to create vertical movement effects. Use keyframes to define the animation path and combine with timing functions for smooth, professional-looking transitions.

Updated on: 2026-03-15T13:35:02+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements