How to Draw a Cylinder in CSS

A step-by-step guide on how to draw this simple shape with CSS

Alvaro Montoro
2 min readDec 22, 2022

There are many ways to draw a cylindrical shape with HTML and CSS, and many guides on creating one. Most of them involve multiple HTML tags or use pseudo-elements. This guide shows how to do it with a single HTML tag (no pseudos) and just a few lines of CSS.

Step 1: Writing the HTML

<div class="cylinder"></div>

Wait… there’s no need for extra elements or pseudo-elements as most other guides say you do? No, not at all! Let’s keep it simple. One cylinder, one HTML element.

Step 2: Styling the HTML

.cylinder {
/* whatever values/units you want */
width: 250px;
height: 400px;
border-radius: 100% / 80px;
background:
radial-gradient(50% 40px at 50% 40px, #0003 99.99%, #0000 0),
radial-gradient(50% 40px at 50% calc(100% - 40px), #fff3 99.99%, #0000 0),
red;
}

And a short explanation of what it does:

  • First, we have the size of the container. You can put whatever you want.
  • Then, we have a border-radius. It has two values separated by a slash. The second one conditions how much curvature will be at the top and bottom of the cylinder.
  • Finally, we draw the circles as radial gradients (notice how the size is half the curvature we specified on the border-radius).

And that’s it! One HTML tag and four CSS properties. No need to overcomplicate things with multiple elements or relative/absolute positioning.

If you are noticed, there’s a 99.99% instead of 100% in the radial gradients. This is because of a bug on Safari that creates weird gradients when stopping exactly at 100%. So, we used 99.99% instead.

Step 3 (optional): Adding Custom Properties

If we use custom properties, we can make the cylinder more “generic,” so it adjusts the border and radius automatically by just changing one value in one place (instead of several locations):

.cylinder {
/* this variable will define how big the curve will be */
--r: 40px;
/* whatever values/units you want */
width: 250px;
height: 300px;
background:
radial-gradient(50% var(--r) at 50% var(--r), #0003 99.99%, #0000 0),
radial-gradient(50% var(--r) at 50% calc(100% - var(--r)), #fff3 99.99%, #0000 0),
red;
border-radius: 100% / calc(var(--r) * 2);
}

Again, that’s it! All in barely ten lines of code: a single HTML element, a single CSS ruleset. Here’s a demo:

--

--

Alvaro Montoro

Full-Stack Software Engineer, Mobile Developer, Web technologies enthusiast. CSS aficionado. Twitter: @alvaro_montoro