CSS Transitions and Animations

A basic introduction to creating simple CSS transitions and animations to enhance user experience.


CSS Transitions

Creating Basic Transitions

CSS transitions allow you to smoothly animate changes to CSS property values over a given duration. They provide a way to create engaging and interactive user interfaces. Instead of a property instantly snapping to its new value, a transition gradually changes the property value, creating a visual animation. The core of a CSS transition involves specifying which properties should transition, how long the transition should take, and what timing function should be used to control the animation's pace. The main properties involved in CSS transitions are:

  • transition-property: Specifies the CSS property to which the transition effect should be applied. Common values include `all` (to apply to all properties that can be animated), `color`, `background-color`, `opacity`, `transform`, `width`, `height`, etc.
  • transition-duration: Defines how long the transition effect should take to complete, specified in seconds (s) or milliseconds (ms). A longer duration makes the animation slower and more gradual.
  • transition-timing-function: Specifies the acceleration curve of the transition. Common values include:
    • `ease`: (default) Slow start, then fast, then slow end.
    • `linear`: Constant speed throughout the transition.
    • `ease-in`: Slow start.
    • `ease-out`: Slow end.
    • `ease-in-out`: Slow start and slow end.
    • `cubic-bezier(n,n,n,n)`: Allows for custom timing functions.
  • transition-delay: Specifies a delay (in seconds or milliseconds) before the transition effect starts.

You can combine these properties into a single `transition` shorthand property: transition: property duration timing-function delay;

Practical Examples

Example 1: Hover - Color & Background Color

This button changes its background color and text color on hover.

Example 2: Focus - Opacity

This input field becomes slightly transparent when focused.

Example 3: Active - Transform: Translate

This button moves slightly to the right when clicked (active state).

Example 4: Hover - Transform: Rotate

Rotate

This box rotates 180 degrees on hover.

Example 5: Hover - Width/Height

Size Change

This box increases in size (width and height) on hover.

Example 6: Combined Transitions (all)

Complex

This box changes multiple properties on hover using `transition: all`.