Let's start with a very simple landing page.
Here is the index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Use CSS for Animation</title>
<link rel="stylesheet" href="styles/animation.css">
</head>
<body>
<header>
<h2>Welcome to my animation world!</h2>
</header>
</body>
</html>
This is a very simple page with only <header> and <h2> to be styled for animation.
First, I need to style the <header> element.
👉 center the <h2> tag :
display: flex;
justify-content: center;
align-items: center;
header {
display: flex;
justify-content: center;
align-items: center;
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
color: whitesmoke;
min-height: 100vh;
overflow: hidden;
}
To add an animated background image, use ::before pseudo element.
header::before {
animation: 5s 1s cubic-bezier(0,.81,0,.87) forwards fade-slide-down ;
// multiple background starting from front layer
background: linear-gradient(to bottom, rgba(0, 0, 0, 0),rgba(0,0,0,.8)),
url(../img/hero.png) no-repeat bottom;
background-size: contain;
opacity: 0;
content: '';
position: absolute;
top:0;
right: 0;
bottom: 0;
left:0;
z-index: -1;
}
@keyframes fade-slide-down {
0% {
opacity: 0;
transform: translateY(-4rem);
}
100%{
opacity: 1;
transform: none;
}
}
Let's see what is going on here.
👉 set the background image position:
position: absolute;
top:0;
right: 0;
bottom: 0;
left:0;
The background has two layers with a linear-gradient on the front layer to soften the brightness of the image.
background: linear-gradient(to bottom, rgba(0, 0, 0, 0),rgba(0,0,0,.8)),
url(../img/hero.png) no-repeat bottom;
Then the animation is defined with 5s duration and 1s delay. The timing function is customized using cubic-bezier function. 'forwards' will set the background image as the last frame, it is the convention to keep the animation-name at the end of the line.
animation: 5s 1s cubic-bezier(0,.81,0,.87) forwards fade-slide-down ;
In order to animate the title, I like to see it comes from left of the screen, cross it with the opacity growing, all the way to 25% beyond the right of the screen, then move back to the center with opacity to reach fullness.
h2 {
color: #4b535b;
font-size: 4rem;
animation: 3s cubic-bezier(0,.85,.68,.82) forwards changeH2;
}
@keyframes changeH2 {
0% {
transform: translateX(-100%);
opacity: 0;
}
50% {
transform: translateX(25%);
opacity: 75%;
}
100% {
transform: none;
opacity: 1;
}
}
Let's check out.
Click the full screen button for a better view:
Some online free tools I used for this article: