Categories
Web development

CSS Transition

The CSS transition property allows elements to change values over a given duration.

CSS transition property

The CSS transition property is shorthand of the following properties:

transition-property

transition-delay

transition-duration

transition-timing-function

Example1:

The transition effect will start when the specified CSS property (width) changes the value. When the cursor moves out of the element, it will gradually change back to its original width.

<!DOCTYPE html>
<html>
<head>
<style> 
.square {
  width: 100px;
  height: 100px;
  background: #2a9d8f;
  transition: width 1s;
}

.square:hover {
  width: 200px;
}
</style>
</head>
<body>

<p>Hover over the square:</p>
<div class="square"></div>

</body>
</html> 

Output:

Hover over the square:

Using the CSS transitions you can change several property values at the same time:

Example2:

<!DOCTYPE html>
<html>
<head>
<style> 
.square {
  width: 100px;
  height: 100px;
  background: #2a9d8f;
  transition: width 1s, height 2s, background-color .5s;
}

.square:hover {
  width: 200px;
  height: 200px;
  background-color: #e9c46a;
}
</style>
</head>
<body>

<p>Hover over the square:</p>

<div class="square"></div>

</body>
</html>  

Output:

Hover over the square:


Example3.

<!DOCTYPE html>
<html>
<head>
<style> 
.square {
  width: 100px;
  height: 100px;
  background: #2a9d8f;
  transition: width 1s, height 1s, transform 1s, background-color 1s;
}

.square:hover {
  width: 200px;
  height: 200px;
  transform: rotate(360deg);
  background-color: #e76f51;
}
</style>
</head>
<body>

<p>Hover over the square below:</p>

<div class="square"></div>

</body>
</html> 

Output:

Hover over the square below:

To specify the speed curve of the transition effect you can use the transition-timing-function property.

The transition-timing-function property can have the following values:

ease (default) – the transition starts slowly, then fast, then ends slowly again.

linear – the transition has the same speed from start to end.

ease-in – the transition starts slowly.

ease-out – the transition end slowly.

ease-in-out – the transition has a slow start and end.

cubic-bezier – allows you to define your own values (n,n,n,n).

The transition-delay property specifies a delay of the transition effect. The transition-delay property is defined by seconds.

Example (2 seconds delay before starting:)

<!DOCTYPE html>
<html>
<head>
<style> 
.square {
  width: 100px;
  height: 100px;
  background: #2a9d8f;
  transition: width 2s;
  transition-delay: 2s;
}

.square:hover {
  width: 200px;
}
</style>
</head>
<body>

<p>Hover over the square:</p>
<div class="square"></div>

</body>
</html>  

Output:

Hover over the square:


Note: The transition effect has a 2 seconds delay before starting.

Enjoy coding!

Read also:

CSS Transition VS. CSS Animation

Introduction to CSS Animation

CSS 3D Transforms