Gradient background with transparent borders
Everybody is asking about how to create gradient borders with transparent backgrounds. But I just had to solve an issue that’s in the opposite situation and learned about background-origin
.
The issue
I have an element that has a CSS gradient as a background, adding transparent borders would create something like this:
Notice the different colors on the borders? Here is the CSS code:
div {
background: linear-gradient(45deg, red, blue);
border: 2px solid transparent;
}
It’s a bit hard to understand what’s going on. So I bumped up the border-width
to 20px
. And now it looks like this:
Now it’s clear, it appears that the gradient background, which is technically a background-image
, is repeating itself. If the borders had colors, they’ll cover up the extra repeats, so normally I wouldn’t notice this. But now I set border colors to be transparent
, I can see the repeats now.
Why this is happening? Now introducing background-origin
.
background-origin
The CSS background-origin
property sets where the background’s top left corner should start. Its value is one of the following keywords (other than the global values like inherit
):
border-box
: Align the background’s top left corner with the border box.padding-box
: Align the background’s top left corner with the padding box. This is the default value, which makes sense, because why would you want to hide part of the background behind the borders?content-box
: Align the background’s top left corner with the content box, which means the padding areas won’t get any background.
This is a CSS property I knew of before but never paid much attention to, until now. After I added background-origin: border-box
, the problem was solved!
div {
background: linear-gradient(45deg, red, blue) border-box;
border: 2px solid transparent;
}