Today I found another way to draw the Sierpinski triangle using pure CSS. There are no recursive divs corresponding to the fractal structure, so it's simpler and performs better.
The method is to use multiple background gradients to draw triangles that are controlled by
Here is how
Actually, the whole code is pretty simple, but I'll try to explain it step by step.
Let's add a
linear-gradient tilted with a degree to make it a triangle.
Add another one with
The previous background has a higher z-index value than the latter one when there are multiple backgrounds. And that's what we wanted: using smaller triangles to fill the holes.
Then add enough levels of gradients. The
is always half the size of the previous one.
Swap background and gradients (triangles) colors.
Remove the top left part with
mask and adjust angle with
See also the live example on CodePen.
How deep it can go
Chrome can render as many triangles as possible but Safari and Firefox don't work well as the triangle is getting smaller.
(I later realized it's caused by the subpixel problem.
So I set the dimension to be
160px, which's divisble by exponential values of 2.)
CSS is kind of different from any other tools. Sometimes you really need to think in CSS in order to develop an elegant solution.
The technique described in this article can be used to generate many interesting patterns too,
That would be another journey.