This is a submission for DEV Challenge v24.03.20, CSS Art: Favorite Snack.
Inspiration
WATERMELON!!!! 🍉
Demo
(Click on the watermelon)
Journey
This is a second submission to the challenge 😳
While this demo uses CSS 3D, it also fakes it a little. This is because of HTML's" flat" nature. Drawing a solid element is not completely possible, so we create hollow versions of them that simulate the solid.
For this drawing, I created the basic shape (a semicircle) and replicated it 15 times, giving each of the slices/layers a slightly different angle. Thanks to that, we have an object that looks nice and three-dimensional at certain angles.
But this way of simulating solid 3D objects presents two main problems:
- When the object is at a 90-degree angle, you can see through it! And as it is animated, you can see a "flash".
- As the front and the back of the layers have the same background, the side view is not ideal as it mixes colors.
For the first issue, the solution was to add a perpendicular layer that is seen at 90-degree angles, avoiding the dreaded see-through flash.
For the second issue, I first changed the background of the in-between layers to a solid color (green), keeping only the red in the edge layers. Then added a pseudo-element (:before
) to hide the red color by rotating it 180 degrees and adding backface-visibility: hidden
.
Finally, after drawing the 3D watermelon, I made it interactive by adding an input of a type checkbox and turning the container into a label. That way, I could use the :has()
selector to apply a mask to the layers when the checkbox is checked.
Adding the mask broke the pseudo-elements in the edges, so I replaced them with two new layers. Maybe not ideal, but it did the trick.
Some other information:
- It uses the
vmin
unit, so it responds to view frame changes, but you could use other units (change thefont-size
value, avoid percentages) - To add additional perspective/3D effect, I added an inset
box-shadow
with semi-transparent black to give an idea of depth. - Instead of copy-pasting the backgrounds or box shadows, I used CSS custom properties, so I just had to update a few values per layer.
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License. You are free to copy and share the code, but not to sell it or use it in commercial projects. Attribution is required.
Top comments (6)
I explained things at a really high level (and poorly, sorry). If you check the code and have any questions, leave a comment, and I will answer here.
Really cool, congrats!
You did awesome! I love the 3D animation.
Smart and simple, congrats
Brilliant
Brilliant 👏