Drawing with CSS: useful, or clever trick?
Last week, Set Studio published the second installment of their excellent Reality Check series. It’s a great post, including a very useful trick with setting font size on a parent to be able to use typographic units like
ex in clever ways.
In it, Andy uses an SVG to create a curved border. It’s easy, it looks great, and it uses the
preserveAspectRatio="none" trick I’ve been so fond of lately. But my initial reaction was that it seemed like a simple enough shape (nearly an ellipse) that it could be achieved with a border radius.
I took a stab at it, and while it’s not perfect, it’s pretty good! I like it because it keeps the markup cleaner and lets the CSS alone focus on the visual design.
That said, it took some fiddling to get the border radii right (or reasonably close to right — see lines 204–210 in the Pen’s CSS). That has me wondering where the line is between drawing with CSS being actually useful, and when it becomes a little too clever. (Don’t get me wrong, I love all of the CSS art out there.) In this particular case, with a simple shape and without resorting to a million stacked gradients in
mask-image, I feel very comfortable with either the CSS-based approach or the SVG-based approach.
On the other hand, I’ve been in situations where being too clever made things more difficult. For example, when someone relied on pseudoelements to create the visual representation of a toggle switch component out of a single div, it was difficult to maintain and even more difficult to style (e.g., a pseudo is a child of its main element, so can’t be more opaque than the element). Thankfully, it was part of a component’s shadow DOM and we had full control over the markup, so I encouraged them to rework it with separate elements for the nub and the track. The resulting CSS was much simpler.
So it seems to me that drawing with CSS can be a great exercise, and is a great way to stretch your skills with CSS. But for most cases in the real world, unless it’s very simple, it seems that sticking with tools that are actually designed for drawing is the better choice.