The
border-image
property (the proper way of creating a gradient border) is not compatible with the
border-radius
property:
Using
border-image
.
.container {
border-width: var(--border-width);
border-style: solid;
border-image: linear-gradient(135deg, var(--color-1), var(--color-2)) 1 stretch;
border-radius: var(--border-radius); /* 👈 this has no effect */
}
We can use a
clip-path
to round the outer corners. But the inner corners remain square:
Using
border-image
and
clip-path
.
.container {
border-width: var(--border-width);
border-style: solid;
border-image: linear-gradient(135deg, var(--color-1), var(--color-2)) 1 stretch;
clip-path: inset(0px round var(--border-radius));
}
So, a nice-looking border with both a gradient and a radius requires a little more CSS (some
calc
-ulations and a pseudo-element):
Using a pseudo element.
.container {
width: calc(100% - (2 * var(--border-width)));
margin: var(--border-width);
position: relative;
border-radius: calc(var(--border-radius) - var(--border-width));
background-color: var(--background);
}
.container::before {
content: "";
position: absolute;
top: calc(var(--border-width) * -1);
right: calc(var(--border-width) * -1);
bottom: calc(var(--border-width) * -1);
left: calc(var(--border-width) * -1);
z-index: -1;
border-radius: var(--border-radius);
background-image: linear-gradient(135deg, var(--color-1), var(--color-2))
}
A colleague showed me Adam Argyle 's awesome pen achieving the same effect by using two backgrounds and clipping them to different box-models 🤯
Using different box models.
.container {
border: var(--border-width) solid transparent;
background-clip:
padding-box,
border-box;
background-image:
linear-gradient(var(--background), var(--background)),
linear-gradient(135deg, var(--color-1), var(--color-2));
background-origin: border-box;
}
The above are, however, still work-arounds or hacks. Neither solution actually uses the
border-image
property.
We frequently use work-arounds to achieve stuff that isn't available with properties, but once the property has landed it feels a bit odd to have to circumvent it?
Shouldn't we simply be able to write:
.container {
border-width: var(--border-width);
border-image: linear-gradient(135deg, var(--color-1), var(--color-2)) 1 stretch;
border-radius: var(--border-radius);
}
The
spec
does not explain why the
border-radius
does not affect a
border-image
. I wonder if it is to do with the
border-image-outset
property or difficulty implementing (the
outline
property was not affected by the
border-radius
property in the beginning).
If you know the answer, please comment on this pen.