How to Use CSS Custom Properties for Smooth Fade-In Animations
Animating elements with CSS custom properties makes your styles more reusable and easy to tweak. The snippet -sd-animation: sd-fadeIn; –sd-duration: 250ms; –sd-easing: ease-in; appears to define a simple, configurable fade-in animation. Below is a concise guide to implementing this pattern and adapting it across a project.
What the properties mean
- -sd-animation: a custom shorthand to select which named animation to run (here:
sd-fadeIn). - –sd-duration: controls the animation length (here:
250ms). - –sd-easing: defines the timing function (here:
ease-in).
CSS implementation
- Define the keyframes for the named animation:
css
@keyframes sd-fadeIn {from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); }}
- Create a base class that reads the custom properties and applies the animation:
css
.sd-animated { animation-name: var(–sd-animation-name, none); animation-duration: var(–sd-duration, 300ms); animation-timing-function: var(–sd-easing, ease); animation-fill-mode: both;}
- Map the shorthand
-sd-animationto the actual animation name using a utility rule:
css
/* When an element sets -sd-animation: sd-fadeIn; this rule assigns the keyframe name /.sd-animated[style=”-sd-animation: sd-fadeIn”] { –sd-animation-name: sd-fadeIn;}
- Example usage in HTML:
html
<div class=“sd-animated” style=”-sd-animation: sd-fadeIn; –sd-duration: 250ms; –sd-easing: ease-in;”> Hello — fades in smoothly.</div>
Tips and variations
- Make the mapping scalable by adding similar attribute selectors for other named animations (e.g.,
sd-slideUp,sd-zoomIn). - Use CSS variables on container elements to control duration/easing for many children at once.
- For accessibility, prefer reduced-motion media query:
css
@media (prefers-reduced-motion: reduce) { .sd-animated { animation: none !important; }}
Summary
This pattern separates animation choice (shorthand), timing, and easing into variables for flexible, reusable animations. Define keyframes, map your shorthand to keyframe names, and use CSS variables to allow easy overrides per element or component.
Leave a Reply