CSS transitions allow you to change property values smoothly (from one value to another) over a specified duration. Instead of an abrupt change, transitions provide a way to animate the changes, enhancing the user experience by making interactions feel more natural and engaging.
This can create visually appealing animations and interactions on your web pages.
Basic Syntax
To apply a transition to an element, you’ll use the transition property. Here’s the general syntax:
transition: property duration timing-function delay;
property: Specifies the CSS property that you want to animate. For example,opacity,transform,background-color, etc.duration: Sets the length of time the transition should take. Use units likeseconds(s) ormilliseconds(ms).timing-function: Determines the speed curve of the transition. Common values include:linear: Constant speed.ease: Slow start, fast middle, slow end (default).ease-in: Slow start.ease-out: Slow end.ease-in-out: Slow start and end.
delay: Specifies the delay before the transition starts.
Example
.element {
transition: opacity 0.5s ease;
}
In this example, the element with the class element will fade in and out over half a second, using the ease timing function.
Multiple Transitions
You can apply multiple transitions to a single element by separating them with commas:
transition: opacity 0.5s ease, transform 0.3s linear;
Hover Effect Example
Here’s a practical example of a hover effect using transitions:
.button {
background-color: blue;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
transition: background-color 0.3s ease-in-out, transform 0.2s ease-in-out;
}
.button:hover {
background-color: green;
transform: scale(1.1);
}
When you hover over the button, its background color will change smoothly and it will scale slightly.
Common Use Cases
- Hover Effects: Change colors, sizes, or positions when users hover over elements.
- Modal Animations: Smoothly appear and disappear modals or dialogs.
- Interactive Menus: Animate dropdowns or sliding menus.
- Image Galleries: Transition between images with fading or sliding effects.
Key Points to Remember
- Transitions only work when the property’s value changes.
- The
transition-property,transition-duration,transition-timing-function, andtransition-delayproperties can also be used individually for more granular control. - For more complex animations, consider using CSS animations or JavaScript libraries like GSAP.