Premium CSS Course

CSS Transitions

CSS Transitions allow you to smoothly change property values of an element over a specified duration. These transitions enable a smooth, interactive user experience, making websites feel more dynamic.

What are CSS Transitions?

A CSS transition is triggered when a property value changes, and it allows you to animate the change. This is particularly useful for hover effects, focus states, or when you need to animate elements based on user interaction.

Basic Syntax of a CSS Transition

To use transitions, you define the following four properties:

Example of a Basic Transition

In this example, we apply a smooth color change on hover using CSS transitions:


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

        .button:hover {
            background-color: #45a049;
        }
    

When you hover over the button, the background color smoothly transitions from #4CAF50 to #45a049 in 0.3 seconds with an easing effect.

Multiple Property Transitions

You can animate multiple properties simultaneously. For example, you can transition both the background-color and transform properties:


        .box {
            width: 100px;
            height: 100px;
            background-color: #4CAF50;
            transition: background-color 0.5s, transform 0.3s ease-in-out;
        }

        .box:hover {
            background-color: #45a049;
            transform: scale(1.2);
        }
    

In this example, the box element changes color and scales up when hovered over. The background color transitions over 0.5 seconds, while the scaling happens in 0.3 seconds with an easing effect.

Transition Timing Functions

The transition-timing-function property defines how the transition will progress over time. Common timing functions include:

Transition Delay

If you want to add a delay before the transition starts, use the transition-delay property. The transition will wait for the specified time before it begins:


        .delayed-box {
            width: 100px;
            height: 100px;
            background-color: #4CAF50;
            transition: background-color 0.5s ease-in-out 1s;
        }

        .delayed-box:hover {
            background-color: #45a049;
        }
    

In this example, the background color will change after a 1-second delay, with the transition taking 0.5 seconds to complete.

Best Practices for CSS Transitions