How to make a fade-in animation
Short answer
Describe the animation in @keyframes and attach it with animation:
<style>
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
.notice { padding: 12px; background: honeydew; animation: fade-in 1.5s ease-out; }
</style>
<div class="notice">Your order has been placed</div>The animation runs once when the element appears on the page. Rerun the example to see it again.
Fading in with a slide
Usually a small upward slide is added to the opacity:
<style>
@keyframes rise { from { opacity: 0; translate: 0 16px; } }
.item { padding: 10px; margin-bottom: 6px; background: lavender; animation: rise 0.6s ease-out both; }
.item:nth-child(2) { animation-delay: 0.2s; }
.item:nth-child(3) { animation-delay: 0.4s; }
</style>
<div><div class="item">First</div><div class="item">Second</div><div class="item">Third</div></div>If you give only from, the end state is the element's normal styles. both holds the first frame during the delay so the items do not flash.
Elements shown later
For an element that appears from display: none there is @starting-style — it sets the styles a transition starts from:
.toast { transition: opacity 0.3s; }
@starting-style { .toast { opacity: 0; } }Common mistake
The element flickers: it shows, disappears and only then fades in. That happens with animation-delay but no animation-fill-mode: both — during the delay the element shows in its normal state. Add both, as in the second example.
Functions used in this recipe
- animation — Runs a `@keyframes` animation on an element.
- @keyframes — Describes the steps of an animation that is then started with the `animation` property.
- opacity — The transparency of the whole element together with its content.
- @starting-style — Sets the styles an element starts from when it first appears, so a `transition` can animate its entrance.