CSS Transitions

Home / CSS / CSS Transitions

CSS Transitions


CSS Transition:

CSS transitions allow you to smoothly animate property changes on elements over a specified duration. They are a valuable tool for creating engaging and interactive user interfaces. Transitions can be applied to a wide range of CSS properties, such as color, size, position, opacity, and more.

Here's how to use CSS transitions:

Basic Syntax:

To create a simple transition, you need to specify the property you want to animate, the duration of the transition, and the timing function (how the animation progresses). Here's the basic syntax:

<style>
    element {
      transition: property duration timing-function delay;
    }
  </style>

property: The CSS property you want to animate.

duration: The duration of the transition in seconds (s) or milliseconds (ms).

timing-function: The timing function that controls the acceleration of the animation (e.g., ease, linear, ease-in, ease-out, ease-in-out, cubic-bezier(), etc.).

delay (optional): The delay before the transition starts, in seconds (s) or milliseconds (ms).

Transition on Hover:

One common use case for transitions is to apply them when an element is hovered over. For example, you can smoothly change the background color of a button when a user hovers their mouse pointer over it:

 
<style>
    button {
      background-color: #3498db;
      transition: background-color 0.3s ease-in-out;
    }

    button:hover {
      background-color: #2980b9;
    }
  </style>

In this example, when the mouse hovers over the button, the background color will transition smoothly from #3498db to #2980b9 over a duration of 0.3 seconds with an ease-in-out timing function.

Transition Multiple Properties:

You can transition multiple properties simultaneously by separating them with commas within the transition property:

 
<style>
    element {
      transition: property1 duration timing-function, property2 duration timing-function;
    }
  </style>

For example, you can transition both the background color and the font size of a button:

<style>
    button {
      background-color: #3498db;
      font-size: 16px;
      transition: background-color 0.3s ease-in-out, font-size 0.3s ease-in-out;
    }

    button:hover {
      background-color: #2980b9;
      font-size: 18px;
    }
  </style>

Removing Transitions:

To remove a transition on an element, set the transition property to none. This will make the property changes instant without any animation.


<style>
    element {
      transition: none;
    }
  </style>

Transition Shorthand:

There is a shorthand property called transition that allows you to set all transition-related properties in one declaration. It follows the order: property duration timing-function delay.


<style>
    element {
      transition: background-color 0.3s ease-in-out, font-size 0.3s ease-in-out;
    }
  </style>