Draw with CSS: Using CSS To Draw Elements

With clever use of CSS properties, it is in fact possible to draw very complex shapes. All the shapes below were drawn with CSS alone. It might be that CSS isn’t the best way to render shapes in the browser window, but it’s very fast and included for “free” on all modern browsers. Learn how to draw with CSS below.

Draw with CSS: Border-Radius

Setting the border-radius of an object can round off the corners. When used with more dramatic values, it can draw circular and elliptical shapes.

Circle

If we want to start a simple circle, we could use something like the following:

The linear gradient sits on top of the blue but below the grey. It’s also barely opaque, so it only creates a minor effect. This creates the illusion of depth, making our two-dimensional cylinder appear slightly more three-dimensional.

Uneven Border Radius and Slash Notation

This cylinder in both its forms relies on an important property: uneven border-radius and slash notation. If we set two values with a slash, like 100% / 50%, those values individually sets the horizontal border radius separately from the vertical border radius, and in that order. This creates unequal or uneven border curves. You can learn more about uneven border-radius syntax from MDN.

The big trick with this shape (or combination of shapes) is the use of the transform: rotate property. This works like it sounds, and spins the element around its central point. Positive degree values rotate the shape clockwise. Negative degree values rotate the shape counter-clockwise.

In shapes with zero height and width, the object is rotated about the point that would be the center of the shape if it had dimensions. This means that, with uneven border values, rotations may appear to happen about a position slightly outside the element, which is normal but confusing until you see it.

Conclusion:

Drawing with CSS is an under-utilized use of style sheets. Developers tend to reach immediately for images, SVGs, or even JavaScript. But there’s no reason to bring more than is necessary into your code. Sure, drawing a five-pointed star with CSS isn’t exactly easy or maybe even sensible. But for basic buttons, you can style shapes far more dramatically than you might realize. Try it out on your next project and see what you think.