Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How hovering over a division element to gradually change the width in CSS ?
To gradually change the width of a division element on hover in CSS, we use the transition property combined with the :hover pseudo-class. This creates smooth animations that enhance user experience.
Syntax
selector {
width: initial-width;
transition: width duration timing-function delay;
}
selector:hover {
width: new-width;
}
Transition Property
The transition property is a shorthand that controls how CSS properties change over time. It consists of four main components
| Property | Description | Default Value |
|---|---|---|
transition-property |
Specifies which CSS property to animate | all |
transition-duration |
Duration of the animation | 0s |
transition-timing-function |
Speed curve of the transition | ease |
transition-delay |
Delay before animation starts | 0s |
Example: Basic Width Transition
The following example demonstrates a simple width transition on hover
<!DOCTYPE html>
<html>
<head>
<style>
.box {
width: 150px;
height: 100px;
background-color: #3498db;
transition: width 2s ease;
color: white;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.box:hover {
width: 300px;
}
</style>
</head>
<body>
<div class="box">Hover me!</div>
</body>
</html>
A blue box with "Hover me!" text that smoothly expands from 150px to 300px width over 2 seconds when hovered.
Example: Advanced Width Animation
This example includes multiple transition effects and custom timing
<!DOCTYPE html>
<html>
<head>
<style>
.animated-div {
width: 200px;
height: 150px;
background: linear-gradient(45deg, #e74c3c, #f39c12);
border-radius: 10px;
transition: width 1.5s cubic-bezier(0.4, 0, 0.2, 1);
color: white;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
margin: 20px;
cursor: pointer;
}
.animated-div:hover {
width: 450px;
}
</style>
</head>
<body>
<h2>Smooth Width Animation</h2>
<div class="animated-div">Hover for smooth expansion</div>
</body>
</html>
A gradient-colored rounded box that smoothly expands from 200px to 450px width with a custom cubic-bezier timing function when hovered.
Timing Functions
You can control the animation speed using different timing functions
| Function | Description |
|---|---|
ease |
Slow start, fast middle, slow end (default) |
linear |
Same speed from start to end |
ease-in |
Slow start, then fast |
ease-out |
Fast start, then slow |
cubic-bezier() |
Custom timing curve |
Conclusion
The CSS transition property with :hover provides an elegant way to create smooth width animations. This technique enhances user interaction and creates engaging visual effects with minimal code.
