Today, I dived into the world of CSS transitions, and I was excited to see how a small piece of code can make a website feel more smooth and interactive. In this post, I’ll share what I learned and how transitions work in CSS.
What Are CSS Transitions?
CSS transitions allow you to change property values smoothly (over a given duration) instead of instantly. For example, instead of a button changing color immediately when hovered, transitions let that color change happen gradually.
Basic Syntax
Here’s the basic syntax of a CSS transition:
selector {
transition: property duration timing-function delay;
}
-
property: The CSS property you want to animate (e.g.,
background-color,width,transform) -
duration: How long the transition takes (e.g.,
0.5s,1s) -
timing-function (optional): The speed curve (e.g.,
ease,linear,ease-in,ease-out,ease-in-out) - delay (optional): The delay before the transition starts
Example: Button Hover Effect
<button class="btn">Hover Me</button>
.btn {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
transition: background-color 0.3s ease;
}
.btn:hover {
background-color: #2E7D32;
}
When you hover over the button, the background color changes smoothly from green to dark green in 0.3 seconds.
Transitioning Multiple Properties
You can transition multiple properties like this:
.box {
width: 100px;
height: 100px;
background-color: red;
transition: width 0.5s, background-color 0.3s;
}
.box:hover {
width: 200px;
background-color: blue;
}
Tips I Learned
- Only animatable properties can be transitioned (e.g.,
color,background-color,transform,opacity,width,height, etc.) - Use
transition: allif you want all animatable properties to transition — but use it carefully, as it can affect performance. - Combine transitions with pseudo-classes like
:hover,:focus, or:activefor better interactivity.
Final Thoughts
Learning CSS transitions opened my eyes to how much they can improve the user experience of a website. They're simple to use but make a big impact visually. I’m excited to explore more about animations using @keyframes and the animation property next!
Top comments (0)