CSS Transitions

What Are Transitions?

Transitions allow CSS property changes to occur gradually over time instead of happening instantly. This makes UI interactions feel smoother and more responsive.

Transition Properties

  • transition-property: the CSS property to animate
  • transition-duration: time the animation lasts
  • transition-timing-function: acceleration style controlling the speed curve of the animation.
    Common values:
    • ease — starts slow, speeds up, then slows again (default)
    • linear — constant speed from start to finish
    • ease-in — slow start, speeds up at the end
    • ease-out — fast start, slows down at the end
    • ease-in-out — slow start and end, faster in the middle
    • cubic-bezier(n,n,n,n) — custom curve definition
    • steps(n, start|end) — creates a stepped transition
  • transition-delay: how long to wait before starting

Shorthand Syntax

transition: background-color 0.3s ease-in 0.1s;

This is a concise way to apply multiple transition settings at once.

Visual Examples

Background Color Transition:

Hover to change background
.transition-box {
  width: 200px;
  height: 100px;
  background-color: lightblue;
  transition: background-color 0.5s ease;
}

.transition-box:hover {
  background-color: lightcoral;
}

Width Transition:

.transition-width {
  width: 100px;
  height: 50px;
  background-color: lightgreen;
  transition: width 0.5s ease-in-out;
}

.transition-width:hover {
  width: 200px;
}

Button Transition:

.transition-button {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.3s ease;
}

.transition-button:hover {
  background-color: #45a049;
  transform: scale(1.05);
}

Best Practices

  • Use short durations (e.g., 0.2s to 0.5s) for responsiveness
  • Avoid transitioning properties like height: auto
  • Use transform and opacity for better performance

Practice Prompt

Create a button that smoothly changes its color and size when hovered using transition.

<button class="smooth-button">Hover Me</button>

<style>
  .smooth-button {
    background-color: #4CAF50; /* default green */
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.4s ease, transform 0.4s ease;
  }

  .smooth-button:hover {
    background-color: #45a049; /* darker green */
    transform: scale(1.1); /* slightly bigger */
  }
</style>

You can copy and paste this code in your IDE to run!

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic