DEV Community

Cover image for CSS 3D art: a 3D translucent rainbow-colored donut
Maciek Fitzner
Maciek Fitzner

Posted on • Originally published at mackfitz.hashnode.dev on

CSS 3D art: a 3D translucent rainbow-colored donut

3D geometries were always THE thing that I loved CSS for - regardless of its performance and practicality of it. But to really make the best of it, I needed trigonometry - for which I originally used PHP and then switched to Sass/SCSS (a CSS preprocessor).

But now it's here - in CSS calcs!

sin(), cos(), tan(), asin(), acos() and atan() have been under consideration for the longest time. I remember them being old news when I first looked into it in 2019, and then no news for a couple of years. Thought they'd never happen.

Then one day last year, Safari quietly rolled out the whole lot - and then also sqrt(), pow() and hypot(). Last December Firefox picked up. But it seemed like that was it. The usual outliers, who usually lagged behind, did something weird - and the cool kids couldn't be bothered.

But finally, Chrome 111 was released and it too supports trigonometry in calcs.

So I went to town with it! Here's a live demo on Codepen

You can have some fun with it, too!

  • you click on the numbers on the left and the fractions on the right (the currently selected option is the one glowing white). The input labels might be slow/stubborn, so you might need to click again for them to react.

  • you can modify the shape of the ring and the cross-section - the numbers denote how many sides the basic polygonal shape has. By default it's at 16, approximating a circle - and 32 is even closer. But you can go lower: you've got an octagon, a hexagon, a pentagon, a square and a triangle

  • you can change the girth, too: it's 1/4 by default - meaning the girth is a quarter of the ring's diameter. 1/10 will look like a bracelet. 1/3 is like a real beefy donut. 1/2 gives you a torus with no visible gap inside, and at 2/3 the ring intersects itself. And in case you were wondering, 1/1 would simply be a sphere.

  • Depending on your device, the performance might be slow at higher segment numbers. On mine it runs smoothly up to 16 segments, and starts stuttering at 32.

  • Performance depends on the browsers, too. The demo seems to run faster on Firefox than Chrome.

  • it should run on mobile, too - but I haven't actually checked. I still only use my 13-year-old Nokia 1616.

The math behind it all is fascinating ;) I'm doing a series of 3D CSS tutorials, but it's going slow, and I haven't even gone over the cube entirely - and haven't even touched on trigonometry yet - so getting all the way to the torus might take a while.

Speaking of which, here are the tutorials:

CSS 3D: The Cube - Part I
CSS 3D: The Cube - Part II

Top comments (0)