In this lesson, we will explore CSS transitions and animations, which allow us to add motion and visual effects to web elements.
CSS transitions allow us to smoothly change the style of an element over a specified duration. By specifying the CSS properties to transition and the desired duration, we can create animations that are triggered by certain events, such as hovering over an element or applying a CSS class.
Here's an example of how to create a simple CSS transition:
1.box {
2 width: 100px;
3 height: 100px;
4 background-color: blue;
5 transition-property: width;
6 transition-duration: 1s;
7 transition-timing-function: ease-in-out;
8}
9
10.box:hover {
11 width: 200px;
12}
In this example, we have a box element with a width of 100 pixels. When we hover over the box, the width transitions smoothly to 200 pixels over a duration of 1 second. The transition-property
specifies the CSS property to transition, and the transition-duration
specifies the duration of the transition.
CSS animations provide more control over the motion and appearance of elements. They allow us to define keyframes that specify different styles at different points in time. By specifying the keyframes and the desired animation properties, we can create complex and dynamic animations.
Here's an example of how to create a CSS animation:
1@keyframes slide-in {
2 0% {
3 transform: translateX(-100%);
4 }
5 100% {
6 transform: translateX(0%);
7 }
8}
9
10.box {
11 width: 100px;
12 height: 100px;
13 background-color: blue;
14 animation-name: slide-in;
15 animation-duration: 1s;
16 animation-timing-function: ease-in-out;
17}
In this example, we define a keyframe animation called slide-in
. The animation starts with the element translated 100% to the left and ends with the element at its original position. The animation-name
specifies the name of the animation, and the animation-duration
specifies the duration of the animation.
By using CSS transitions and animations, we can enhance the user experience by adding motion and visual effects to web elements.