DEV Community 👩‍💻👨‍💻

Diana Le
Diana Le

Posted on • Updated on

Animated Sky Using CSS Keyframes, Gradients and Transform

Animated Sky Using CSS Keyframes, Gradients and Transform

This was a fun weekly Codepen challenge. Animation is one area of CSS that I don't really get to use at work so this was my opportunity to work more with keyframes and transforms.

How to Animate the Sun on a Curve

I immediately had flashbacks to Flash and tweening and wondered how it was possible to do this only using CSS. Then I found this Stack Overflow post which just uses CSS transform: rotate and puts the sun on a corner of the div. Simple and effective. (Don't look for astronomical accuracy with how the moon and sun orbit though!)

How to Animate Gradients with CSS

Spoiler alert: you can't. You can only use opacity, which is what I used in combination with keyframes. This was the most time-consuming part because I wanted the sky's colors to reflect the real day, which meant not making every single gradient each take up the same percentage, so this was a lot of trial and error with changing the opacity percentages.

Add some JavaScript

I wanted to keep as much of the code in CSS as possible, so the gradients and sun/moon transitions are all done using CSS. I could have built the stars in the night sky manually via HTML and CSS, but decided that randomly generating them and being able to update the total number was more efficient. Plus I need some vanilla JavaScript practice.

Since the animation loops infinitely, I figured I'd add a pause/play button for people who want to check out the code without being distracted.

Top comments (3)

nagendradevara profile image
Nagendra Devara

Nice post and cool Animations

balagopinaath profile image
Bala Gopinaath

Nice one 🎉

cmuralisree profile image
Chittoji Murali Sree Krishna

Nice 👍

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.