Gradient Border

A simulated gradient border built with Tailwind CSS and multiple backgrounds.

Hello, gradient

A gradient border implemented with multiple backgrounds.

This technique uses the background-clip CSS property, which controls whether an element's background is only drawn to the edge of its padding area (padding-box) or whether it extends fully to include its border (border-box).

To achieve the effect, a transparent 1px border is added. Then, two backgrounds are set:

  • The first uses padding-box to draw a solid black background that spans only the inner area.
  • The second uses border-box to draw a gradient background that includes the border.

The result is that the gradient background is only visible along the 1px border.

When multiple backgrounds are set via the CSS background property, the first one is rendered on top and the last one on bottom. The first one needs to be the solid color so that it masks the rest of the gradient background. But when setting multiple backgrounds, only the last background can be set as a solid color. Thus, the first background must be set as a linear-gradient from the solid color to the same solid color for the property to be valid.

Here's the final CSS:

border: 1px solid transparent;
background: padding-box linear-gradient(rgb(30 41 59), rgb(30 41 59)),
  border-box linear-gradient(rgb(255 255 255), rgb(255 255 255 / 0.1));

And here it is parameterized with CSS variables:

--background: "30 41 59";
--highlight: "255 255 255";

border: 1px solid transparent;
background: padding-box linear-gradient(rgb(var(--background)), rgb(var(--background))),
  border-box linear-gradient(rgb(var(--highlight)), rgb(var(--highlight) / 0.1));

The demo above uses Tailwind CSS's arbitrary properties to set multiple backgrounds directly on the element, and a more complex gradient to achieve the brightened upper-left corner:

import { CSSProperties } from "react";

function Component() {
  return (
          "--background": "30 41 59",
          "--highlight": "255 255 255",

            "linear-gradient(rgb(var(--background)), rgb(var(--background)))",
          "--border-color": `linear-gradient(145deg,
            rgb(var(--highlight)) 0%,
            rgb(var(--highlight) / 0.3) 33.33%,
            rgb(var(--highlight) / 0.14) 66.67%,
            rgb(var(--highlight) / 0.1) 100%)
        } as CSSProperties
      className="flex aspect-[2/1] w-full max-w-md flex-col items-center justify-center rounded-xl border border-transparent p-8 text-center
      <p className="text-xl font-medium text-white">Hello, gradient</p>