Time units in CSS specify a duration. They are crucial for defining how long animations and transitions should last or when they should start.
Example 1: s
(seconds) in Transition Duration
/* Sets a smooth transition for the 'background-color' property over 0.5 seconds */
.my-element {
background-color: blue;
transition: background-color 0.5s ease-in-out; /* 0.5 seconds duration */
}
.my-element:hover {
background-color: red;
}
Explanation This example demonstrates using s
for transition-duration
. The background color change from blue to red will take 0.5 seconds, creating a subtle animation effect. This enhances user interaction.
Example 2: ms
(milliseconds) in Animation Duration
/* Defines a 'fade-in' animation that completes in 750 milliseconds */
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
.fade-item {
opacity: 0;
animation: fade-in 750ms forwards; /* 750 milliseconds duration */
}
Explanation Here, ms
defines the animation duration. The .fade-item
will gradually become visible over 750 milliseconds, providing a smooth entrance effect. Milliseconds offer finer control for subtle timing.
Example 3: s
for Animation Delay
/* Delays the 'slide-in' animation by 1 second before it starts */
@keyframes slide-in {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
.delayed-item {
animation: slide-in 0.8s ease-out 1s forwards; /* 1 second delay */
}
Explanation This illustrates s
for animation-delay
. The slide-in
animation will wait for 1 second before executing, useful for orchestrating multiple animations. This ensures a staggered visual presentation.
Example 4: ms
for Transition Delay
/* Delays the 'color' transition by 200 milliseconds */
.hover-effect {
color: black;
transition: color 0.3s ease-in-out 200ms; /* 200 milliseconds delay */
}
.hover-effect:hover {
color: green;
}
Explanation In this code, ms
is used for transition-delay
. The color change will be delayed by 200 milliseconds after the hover event. This can create a slight pause for a more refined user experience.
Example 5: Combining s
and ms
for precise control
/* Applies a bounce animation with 0.6s duration, 0.1s delay, and 200ms iteration delay */
@keyframes bounce {
0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
40% { transform: translateY(-30px); }
60% { transform: translateY(-15px); }
}
.bouncing-element {
animation: bounce 0.6s ease-out 0.1s infinite; /* 0.6s duration, 0.1s delay */
/* Note: Animation iteration delay is not a direct CSS property,
but achieved through keyframe timing or multiple animations.
This example focuses on `s` and `ms` in duration/delay. */
}
Explanation While direct iteration delay isn't a single property, this demonstrates using s
for duration and delay. Precision in timing with s
and ms
allows for complex and fluid animations, enhancing web interactivity.