Implementing CSS Animations and Transitions
Defining Keyframe Animations
Complex, multi-step sequences are constructed using the @keyframes rule, which is then applied to an element via the animation shorthand.
@keyframes expandIn {
0% {
opacity: 0;
transform: scale(0.5);
}
100% {
opacity: 1;
transform: scale(1);
}
}
.loader {
animation: expandIn 1.2s ease-out forwards;
}Applying CSS Transitions
Transitions provide a smooth interpolation between property values when a state change occurs, such as on :hover.
.panel {
width: 150px;
height: 150px;
background-color: #4b6584;
transition: width 0.5s ease, height 0.5s ease;
}
.panel:hover {
width: 250px;
height: 300px;
}Interactive Example
The markup below demonstrates a keyframe animation playing on load, alongside a transition triggered by a checkbox, and a JavaScript-driven visibility toggle.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Motion Demo</title>
<style>
.intro-box {
width: 120px;
height: 50px;
background-color: #6a89cc;
animation: fadeSlide 1s ease-in;
}
@keyframes fadeSlide {
from {
opacity: 0;
transform: translateY(-20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
#switch:checked ~ .shift-box {
margin-left: 80px;
opacity: 1;
}
.shift-box {
width: 90px;
height: 90px;
background-color: #82ccdd;
opacity: 0.2;
transition: margin-left 0.6s ease, opacity 0.4s ease 0.1s;
}
.is-hidden {
visibility: hidden;
}
</style>
</head>
<body>
<button onclick="toggleVisibility()">Toggle Intro</button>
<div id="introTarget" class="intro-box"></div>
<br>
<label for="switch">Trigger Shift</label>
<input id="switch" type="checkbox">
<div class="shift-box"></div>
<script>
function toggleVisibility() {
const element = document.getElementById('introTarget');
element.classList.toggle('is-hidden');
}
</script>
</body>
</html>