Single color image
The CSS image() function is intended as a replacement for url() but for the time being it only works with colors. Using image files like image("kitten.jpg") doesn’t work in any browser yet. In this article, I’ll look at why a solid color image can be useful.
In CSS, the gradient syntax can be used to create a single solid color:
div {
background-image: linear-gradient(blue);
}
That works in all browsers, but its counter-intuitive to use gradient syntax to create something that is not a gradient. There’s now a better approach: the CSS image() function can create a solid color image from any color.
div {
background-image: image(blue);
}
When is this useful over using a background-color?
Place a partially transparent color over a background-image
A background-color always lies beneath background images, so doesn’t work for this use case.
.hero {
background-image: image(rgb(0 0 0 / 50%)), url('/mountains.avif');
}
In the future you could also opt to use the new alpha() CSS function.
.hero {
background-image: image(alpha(from black / 50%)), url('/mountains.avif');
}
Moving Mountains
All the control of background-image
Unlike a CSS background-color, background-image comes with all sorts of ways to control its position and size. That may be useful in some scenarios.
div {
background-image: image(yellow);
background-size: 50% 50%;
background-position: center;
background-repeat: no-repeat;
border: solid 2px;
}
Maintain a solid background color when working with background-clip: border-area
.border-gradient {
background-image: image(white), linear-gradient(90deg, oklch(0.62 0.19 240.36) 0%, oklch(0.88 0.24 154.83) 100%);
background-origin: border-box;
background-size: cover;
background-clip: padding-box, border-area;
border: solid 10px transparent;
}
border
Maintain a solid background color when working with background-clip: text
button {
color: transparent;
background-image: linear-gradient(to bottom right in hsl, green, purple), image(white);
background-clip: text, padding-box;
}
Easily swapping between a gradient and a solid color
The following example uses a solid color for light mode, and a gradient for dark mode.
.bg {
background-image: light-dark(image(#efefef), linear-gradient(15deg, #2e3245, #001031));
}
content
It saves one line of code compared to content: ""; background-color: red;.
div::after {
content: image(red);
display: block;
height: 100px;
width: 100px;
}
A default value for a registered custom property
@property --bg {
syntax: "<image>";
inherits: false;
initial-value: image(transparent);
}