Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

linear-gradient(): a generated image along a line

Create color transitions or hard color boundaries as an image value.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

background-image: linear-gradient(to right, red 0 50%, blue 50% 100%);

linear-gradient() generates an image by placing color stops along a straight gradient line. It is an image value, so it works in background-image but cannot replace a color value in color. The default direction is downward. A direction keyword or angle changes the gradient line: 0deg points upward and 90deg points right.

Color stops determine where colors are reached and how transitions occur between them. Repeating a position for adjacent colors makes a sharp boundary instead of a gradual blend. A single color can also have two stop positions, creating a constant-color interval. The gradient does not have the intrinsic pixel dimensions of a downloaded bitmap; the property using it establishes the area to paint.

The example makes the left half red and the right half blue using double-position stops meeting at 50%. Pixels sampled away from that boundary are exactly red and blue. This tests direction, stop placement and image usage without depending on interpolation rounding at the boundary. Transparency and color-space choices require additional care for gradients that actually blend different colors.

Examples

const svg='<svg xmlns="http://www.w3.org/2000/svg" width="8" height="4"><foreignObject width="8" height="4"><div xmlns="http://www.w3.org/1999/xhtml" style="width:8px;height:4px;background:linear-gradient(to right, red 0% 50%, blue 50% 100%)"></div></foreignObject></svg>';
const image=new Image();image.src='data:image/svg+xml;charset=utf-8,'+encodeURIComponent(svg);await image.decode();
const canvas=document.createElement('canvas');canvas.width=8;canvas.height=4;const ctx=canvas.getContext('2d');ctx.drawImage(image,0,0);
const pixel=x=>[...ctx.getImageData(x,2,1,1).data].slice(0,3).join(',');
console.log('left='+pixel(1)+'; right='+pixel(6)+'; color-property='+CSS.supports('color','linear-gradient(red,blue)'));

Result

left=255,0,0; right=0,0,255; color-property=false

The false color-property check confirms that a gradient is an image, even though its arguments describe colors.

Sources