Totally overengineered containers

Creating boxes with beveled corners

This is a pre-AI story of my visual implementation exploration. Nowadays, the general expectation is to solve such cases with magic thinking boxes, but my rebel soul wants to push back on this narrative. I strongly believe it's worth doing things slowly the first time to understand them better. Stick around, and maybe you'll learn something.

I wanted to recreate the effect above, pixel-perfect, for the design system I was working on. Blame Adam for the beautiful design, and me for everything below.

The solution needed to stay responsive, support gradient borders, and perfectly clip transparent content. Don't ask me why I didn't push back on design requirements, I know. Instead let's stay here a while to decompose the problem and learn how to solve it.

Spoiler: Eventually I got a solution that works, and I'm going to lay it all out for you. First, though, we need a little border-radius groundwork; if you're in a hurry or lazy, skip to the final section or grab the instructions for your agent to copy solution — I don't judge really.

Simple 1/4 of a circle

centerrxr + x

Let's start with the basics of CSS border-radius. Empirically everyone see that setting the radius parameter makes browser replace a sharp corner with a rounded one.

The useful mental model is this: a rounded corner is really a quarter circle attached to the box edges. As you increase or decrease the radius, you're not just changing curvature - you're also moving the circle's center point. You will see why this representation is handy later, I promise.

Radius 32px
r
r
center point

Working with border-radius by itself is easy. Once we add border width, things complicate.

With a thin border (around 1px), the result usually looks correct. Increase the width, though, and the corners start breaking. This is a common pitfall, so let’s break down why it happens and how to avoid it.

Radius 32px
Border width 1px
r
r
center point

The issue comes from using the same border radius for both the outer and inner edges. It's an easy trap when building custom rounded boxes. If both edges use the same radius, the border gets thicker in the corner. Turn on the visual guides and you'll see why: the two circles don't share the same center point.

This is a contrived example. In everyday UI work, you usually don't need to think this deeply. Regular CSS borders with border-radius don't have this problem and work great most of the time.

To fix it, the inner radius needs to be smaller than the outer radius by exactly the border width: innerRadius = outerRadius - borderWidth. This keeps both arcs centered on the same point and the border thickness consistent. Try it below with visual guides enabled.

Radius 100px
Border width 1px

Here's a simplified snippet from the playground above.

// outer border radius
<div
  className="relative bg-primary"
  style={{ borderRadius: `${outerRadius}px` }}
>
  {/* inner border radius adjusted for border width */}
  <div
    className="absolute top-0 left-0 w-full h-full bg-background"
    style={{
      borderRadius: `${innerRadius}px`,
      top: `${borderWidth}px`,
      left: `${borderWidth}px`,
    }}
  ></div>
</div>

This is a solid start: it handles simple corners and keeps border width consistent. But it still has two major limitations:

  • It only works for right angles, so shapes with 45-degree corners are still a problem.
  • It doesn't support transparent content, because the effect depends on overlapping two elements.

So we need a different approach for double-rounded corners — a bevel with rounded transitions at both ends. The shared-center idea still works for any angle; we just need to push CSS a bit further.

What defines a border?

If we zoom out, we can define a border as an area between two closed lines. Once we know positions of both lines, we can fill that space with any color. So let's walk through the options.

Box in a box

You've already seen this trick above. "Box in a box" is the same two-layer setup: outer box first, inner box on top, border visible in between. Unfortunately it has major flaw for us it doesn't support transparent content. Hover or tap example below to see why. The visible border is just clever composition of two opaque surfaces.

One simple background image

Another option is a single background image that already contains the border shape. It's easy to set up and supports transparent centers, but it's not parametric: border thickness is baked into the asset. We can scale the image, but to avoid distortion the element has to keep the same aspect ratio.

You can play with example below. Try changing its aspect ratio. The box stays always the same and content is overflowing in some cases.

Another CSS border tricks I knew

Before we jump to the final approach, it's worth looking at the usual CSS tricks:

  • background-clip works nicely for gradients and transparent centers, but it still operates on the same rectangular box primitive with standard border-radius rounding.
  • border-image can scale decorative borders, but it doesn't give us reliable clipping control, and border thickness is not truly parametric.
  • corner-shape is promising, but still experimental, and it can't model the double-rounded bevel corner geometry we're after.

So these are all useful CSS properties, just not for our goal we are after. Full solution had to be responsive with adjustable aspect ratio, support transparency and allow content clipping to specific shape.

Clip-path as a last resort

There's one more approach: clip-path. If you're new to it, clip-path lets you define a custom shape that clips an element's content. In theory we could use it with two SVG paths: one for the outer edge and one for the inner edge to draw the shape we want.

Great thing is that all of the box content will support transparency and borders themselves can be adjusted to shape we can generate dynamically with SVG syntax.

We can draw these corners with either arcs or Bezier curves. Both can produce the same final shape, but arcs are much easier to work with here. SVG Bezier segments are 3rd-degree (cubic), so one Bezier per double corner is not enough; to match the geometry properly, you’d need multiple cubic segments and more complex control-point math.

Why two paths instead of one stroked path? A stroked path looks simpler, but joins are easy to get wrong and can introduce artifacts. Two explicit paths are more predictable and can save us from headaches down the line.

How do we calculate double rounded corners?

Let's define the parameters for a double-rounded corner. We'll build on the previous single-circle example and add one extra parameter: the distance by which the two circle centers are shifted along perpendicular axes. Play with it below to see and understand how it works.

Radius 32px
Distance 0px
d
d
r
r

Next, we join the two arcs with a straight line tangent to both circles. To find its endpoints, draw a radius from each circle’s center at 45° to the box edges, pointing up and left in this example. Connect the points where these radii meet the circles.

Radius 60px
Distance 0px

At this point, the geometry is in a good place: we already have a closed contour built from arcs and tangent connections. From here, the next step is mostly practical - we just need to translate that contour into an SVG path.

Drawing an SVG path

Let's start by refreshing our memory of how SVG path syntax works. In our case we need only a few commands:

  • Move to (M) to set the starting point of the path.
  • Line to (L) to connect the corners with straight lines.
  • Arc (A) to draw the rounded corners.
  • Close path (Z) to close the shape.

I'm not going to dive deep into command details. If you want to learn more, check the MDN SVG path documentation.

Below I wrote pseudo-SVG path syntax to show how the commands work together to create a box with rounded corners. Each corner is defined by an arc, and the lines connect them.

`M 
[corner 0 (top left)]
...line...
...corner 1 (top right)...
...line...
...corner 2 (bottom right)...
...line...
...corner 3 (bottom left)...
...line...
Z`;

Arc command syntax

As I mentioned before we'll use Arc here. And to be precise two Arc commands for each corner. Let's start by looking at command definition below.

M xStart yStart A rx ry rotation large-arc-flag sweep-flag xEnd yEnd
  • M xStart yStart: Start position of the arc. It doesn't belong to the arc itself; it's just where the pen is lifted and moved before drawing the arc.
  • A: Keyword to indicate that we are drawing an arc.
  • rx ry: The x and y radii of the ellipse (in our case, both are the same since we want circular arcs).
  • rotation: The rotation of the ellipse in degrees. For circular arcs, this is typically 0 because it doesn't affect the shape.
  • large-arc-flag: A binary flag (0 or 1) that determines whether the arc should be greater than 180 degrees (1) or less than 180 degrees (0).
  • sweep-flag: A binary flag (0 or 1) that determines the direction of the arc. A value of 0 means the arc will be drawn in a counterclockwise direction, while a value of 1 means it will be drawn in a clockwise direction.
  • xEnd yEnd: The end point of the arc.

Also there's a great article on the SVG Tutorial that explains how to use the Arc command in more detail, so I won't go into it here. The key takeaway is that the Arc command can draw a circular arc between two points, and we can control its direction and size with the flags.

Polar to Cartesian conversion

To use SVG Arc, we need Cartesian coordinates. So we need to convert from polar coordinates with a helper function. Here, 0 degrees points up and angles increase clockwise, since SVG's y-axis points down. Subtracting 90 degrees shifts the trigonometric starting point from the right to the top.

I've prepared a visualization below to help you better understand how the conversion works. It's easy to see now that each trigonometric function corresponds to one axis. Using these functions with the angle gives us the coordinates of the point on the circle's circumference.

function polarToCartesian(
  centerX: number,
  centerY: number,
  radius: number,
  angleInDegrees: number,
): { x: number; y: number } {
  const angleInRadians = ((angleInDegrees - 90) * Math.PI) / 180.0;

  return {
    x: centerX + radius * Math.cos(angleInRadians),
    y: centerY + radius * Math.sin(angleInRadians),
  };
}
Angle0°

Double rounded corner function

We have all of the necessary pieces to construct corner. The tricky part is making it work for all four corners and keeping it readable. Below I prepared a snippet that shows my approach with preview below. You can click and analyze each part independently to understand what happens. My approach probably isn't the most efficient one, but I like it since there are no code branches and it's easy to follow for me. I recommend to start with const firstCircleCenter and later unravel what flags and flip vectors mean.

type CornerPathProps = ... function polarToCartesian(...) { ... } function getCornerStartAngle(corner: CornerPathProps["corner"]): number {  return (180 + 90 * corner) % 360;} export function cornerPath({  corner, = 0  boxSize, = [400, 400]  offset, = 10  d, = 20  radius, = 20}: CornerPathProps): string {  const  = getCornerStartAngle(corner); = 180deg  const  = 45; = 45deg   const xFlipVector = [0, 1, 1, 0];  const yFlipVector = [0, 0, 1, 1];  const  = xFlipVector[corner]; = 0  const  = yFlipVector[corner]; = 0   const  = (...) => ...= distance + 10   const  = (...) => ...= distance + 10   const  = corner % 2; = 0  const  = (corner + 1) % 2; = 1   const : [number, number] = [ = [30, 50]    xDistance(radius + d * oddFlag),    yDistance(radius + d * evenFlag),  ];   const firstCircle = {    start: polarToCartesian(      firstCircleCenter[0],      firstCircleCenter[1],      radius,      startAngle,    ),    end: polarToCartesian(      firstCircleCenter[0],      firstCircleCenter[1],      radius,      startAngle + stepAngle,    ),  };   const : [number, number] = [ = [50, 30]    xDistance(radius + d * evenFlag),    yDistance(radius + d * oddFlag),  ];   const secondCircle = {    start: polarToCartesian(      secondCircleCenter[0],      secondCircleCenter[1],      radius,      startAngle + stepAngle,    ),    end: polarToCartesian(      secondCircleCenter[0],      secondCircleCenter[1],      radius,      startAngle + 2 * stepAngle,    ),  };   const circlePath = (...) => ...   return `${circlePath(firstCircle)} L ${circlePath(secondCircle)}`;} export function createBoxPath(params: Omit<CornerPathProps, "corner">): string {  const pathParts: string[] = [];   for (const corner of [0, 1, 2, 3] as const) {    pathParts.push(      cornerPath({        corner,        ...params,      }),    );  }   return `M ${pathParts.join(" L ")} Z`; = M 10 50 A 20 20 0 0 1 15.86 35.86 L 35.86…}
SVG Path:
M
10 50
A 20 20 0 0 1
15.86 35.86
L
35.86 15.86
A 20 20 0 0 1
50 10
L
350 10
A 20 20 0 0 1
364.14 15.86
L
384.14 35.86
A 20 20 0 0 1
390 50
L
390 350
A 20 20 0 0 1
384.14 364.14
L
364.14 384.14
A 20 20 0 0 1
350 390
L
50 390
A 20 20 0 0 1
35.86 384.14
L
15.86 364.14
A 20 20 0 0 1
10 350

The playground above now includes createBoxPath, the live corner preview, and inline debug values so you can inspect how each parameter changes the generated path.

Putting it all together

Now that we have all the pieces, we can create the final box component by manually drawing SVG shapes and using a clip path to define the borders.

We'll define two closed contours: one for the outer edge and one for the inner edge. The border is the area inside the outer contour but outside the inner one. Unlike the earlier box-in-a-box trick, the inner area is excluded from the border rather than covered with a background-colored box, so transparent content doesn't reveal a border layer underneath.

type DoubleRoundedCorner =  | "top-left"  | "top-right"  | "bottom-right"  | "bottom-left"; type CornerShape = "double-rounded" | "rounded" | "sharp"; type DoubleRoundedBoxProps = {  radius: number;  borderWidth: number;  offset: number;  d: number;  corners?: Partial<Record<DoubleRoundedCorner, CornerShape>>;  children: React.ReactNode;}; function getContentInset({  radius,  borderWidth,  offset,  d,  corners,}: Omit<DoubleRoundedBoxProps, "children">) {  const arcInset = radius * (1 - Math.SQRT1_2);  const cornerInsets = ["top-left", "top-right", "bottom-right", "bottom-left"].map(    (corner) => {      const shape = corners?.[corner] ?? "double-rounded";       if (shape === "double-rounded") return arcInset + d / 2;      return shape === "rounded" ? arcInset : 0;    },  );   return borderWidth + offset + Math.max(...cornerInsets);} export function DoubleRoundedBox({  radius, = 32  borderWidth, = 1  offset, = 10  d, = 20  corners = {}, = 2/4 double-rounded  children,}: DoubleRoundedBoxProps) {  const ref = React.useRef<HTMLDivElement>(null);  const contentMaskId = React.useId();  const borderMaskId = React.useId();  const [boxSize, setBoxSize] = React.useState<[number, number]>();   React.useEffect(() => {    if (!ref.current) return;     const observer = new ResizeObserver(([entry]) => {      setBoxSize([entry.contentRect.width, entry.contentRect.height]);    });     observer.observe(ref.current);    return () => observer.disconnect();  }, []);   const outerRadius = radius + borderWidth; = 33  const inset = getContentInset({ radius, borderWidth, offset, d, corners }); = 30.37  const paths = boxSize    ? getDoubleRoundedBoxPaths({      boxSize,      radius,      borderWidth,      offset,      d,      corners,    })    : null;   return (    <div      ref={ref}      className="relative isolate"      style={{ "--double-rounded-inset": `${inset}px` }}    >      {paths ? (        <svg          aria-hidden="true"          className="pointer-events-none absolute inset-0 h-full w-full"          viewBox={`0 0 ${boxSize[0]} ${boxSize[1]}`}        >          <defs>            <mask id={contentMaskId} maskUnits="userSpaceOnUse">              <path d={paths.innerPath} fill="white" />            </mask>            <mask id={borderMaskId} maskUnits="userSpaceOnUse">              <path d={paths.borderPath} fill="white" fillRule="evenodd" />            </mask>          </defs>        </svg>      ) : null}       <div        className="h-full w-full"        style={paths ? { maskImage: `url(#${contentMaskId})` } : undefined} = Text      >        {children}      </div>       {paths ? (        <div          aria-hidden="true"          className="pointer-events-none absolute inset-0"          style={{            maskImage: `url(#${borderMaskId})`,            background: "currentColor",          }}        />      ) : null}    </div>  );} export function Card({ children }: { children: React.ReactNode }) {  return (    <DoubleRoundedBox radius={32} borderWidth={1} offset={10} d={20}>      <div style={{ padding: "var(--double-rounded-inset)" }}>{children}</div>    </DoubleRoundedBox>  );}

Was it worth it?

That's a lot of geometry for a box. But we now have the shape we wanted, with gradient borders and a transparent center, without relying on a background-colored box to hide the bits we don't want.

The useful part wasn't really the trigonometry. It was treating the border as the space between two contours instead of trying to coax the effect out of overlapping elements. Once that clicked, the rest became a matter of drawing the right lines.

Would I do this for every container? Definitely not. But for this particular one, understanding the geometry was worth the detour. Totally overengineered? Maybe. At least now I and hopefully you know how it works.