Add CSS transition effect for both the width and height property

To add transition effects for both the width and height properties of an element, you can use the CSS transition property. This creates smooth animations when these properties change, such as on hover or focus states.

Syntax

selector {
    transition: width duration, height duration;
    /* or */
    transition: width duration, height duration, ease-function, delay;
}

Example: Transitioning Width and Height on Hover

The following example demonstrates how to add transition effects for both width and height properties when hovering over a box −

<!DOCTYPE html>
<html>
<head>
<style>
    .box {
        width: 150px;
        height: 150px;
        background-color: #3498db;
        margin: 20px;
        transition: width 2s ease, height 2s ease;
    }
    
    .box:hover {
        width: 300px;
        height: 200px;
    }
</style>
</head>
<body>
    <h2>Hover over the box below</h2>
    <p>Watch the smooth transition effect on both width and height.</p>
    <div class="box"></div>
</body>
</html>
A blue rectangular box appears. When you hover over it, the box smoothly expands from 150x150px to 300x200px over 2 seconds, creating a smooth animation effect for both dimensions.

Example: Using Shorthand Transition Property

You can also use the shorthand transition property to apply the same duration and timing to both width and height −

<!DOCTYPE html>
<html>
<head>
<style>
    .square {
        width: 100px;
        height: 100px;
        background-color: #e74c3c;
        margin: 20px;
        transition: all 1.5s ease-in-out;
        cursor: pointer;
    }
    
    .square:hover {
        width: 200px;
        height: 200px;
        background-color: #2ecc71;
    }
</style>
</head>
<body>
    <h2>Hover for Combined Effect</h2>
    <p>This example transitions width, height, and background color together.</p>
    <div class="square"></div>
</body>
</html>
A red square appears. When hovered, it smoothly grows to double its size while changing color from red to green over 1.5 seconds, demonstrating multiple property transitions.

Conclusion

CSS transitions for width and height create smooth animations that enhance user experience. Use individual property transitions for different timings or the all value for uniform effects across multiple properties.

Updated on: 2026-03-15T12:38:04+05:30

647 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements