Perform Animation on CSS max-width

The CSS max-width property can be animated to create dynamic width transitions. This is particularly useful for creating responsive layouts, expandable containers, or smooth resizing effects.

Syntax

selector {
    max-width: value;
    animation: animation-name duration;
}

@keyframes animation-name {
    percentage {
        max-width: value;
    }
}

Example: Basic max-width Animation

The following example demonstrates a smooth transition of the max-width property from its initial state to 250px −

<!DOCTYPE html>
<html>
<head>
    <style>
        .animated-box {
            max-width: 500px;
            overflow: hidden;
            background-color: #3498db;
            color: white;
            border: 2px solid #2c3e50;
            padding: 20px;
            margin: 20px 0;
            animation: shrinkWidth 3s ease-in-out;
        }
        
        @keyframes shrinkWidth {
            0% {
                max-width: 500px;
            }
            30% {
                max-width: 250px;
            }
            100% {
                max-width: 500px;
            }
        }
    </style>
</head>
<body>
    <h2>Max-Width Animation Example</h2>
    <div class="animated-box">
        <p>This container demonstrates max-width animation. Watch as the width smoothly transitions from 500px to 250px and back. This is demo text that will wrap differently as the container width changes during the animation.</p>
    </div>
</body>
</html>
A blue container with white text starts at full width (500px), smoothly shrinks to 250px at 30% of the animation, then expands back to full width. The text content reflows as the container width changes.

Example: Hover-Triggered Animation

This example shows how to trigger max-width animation on hover −

<!DOCTYPE html>
<html>
<head>
    <style>
        .hover-box {
            max-width: 200px;
            height: 100px;
            background-color: #e74c3c;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 20px 0;
            transition: max-width 0.5s ease;
            cursor: pointer;
        }
        
        .hover-box:hover {
            max-width: 400px;
        }
    </style>
</head>
<body>
    <h2>Hover to Expand</h2>
    <div class="hover-box">
        Hover me!
    </div>
</body>
</html>
A red box initially 200px wide that smoothly expands to 400px width when hovered over, then contracts back when the mouse leaves.

Conclusion

Animating the max-width property creates smooth, visually appealing transitions for container resizing. Use keyframes for complex animations or transitions for simple hover effects.

Updated on: 2026-03-15T13:33:32+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements