CSS Linear Gradient with Color Stops Syntax

This guide explains how to define CSS linear gradients using color stops, covering the fundamental linear-gradient() syntax, directional controls, and color-stop placement techniques. You will learn how to transition smoothly between multiple colors, manipulate the midpoint of transitions, and use stop positions to create sharp color boundaries.

Basic Syntax

In CSS, linear gradients are applied using the linear-gradient() function as a value for the background or background-image property. The standard syntax requires at least a direction (optional, defaults to top-to-bottom) and two color stops:

selector {
  background-image: linear-gradient(direction, color-stop1, color-stop2, ...);
}

Defining Direction and Angles

The first argument specifies the orientation of the gradient line. It accepts either directional keywords or specific angle values.

  • Directional keywords: Use the to syntax, such as to top, to bottom, to left, to right, or diagonal pairings like to bottom right.
  • Angle values: Use units like deg (degrees) or turn. An angle of 0deg points straight up, 90deg points to the right, 180deg points down, and 270deg points left.
/* Moves from left to right */
background-image: linear-gradient(to right, blue, green);

/* Moves at a 45-degree angle */
background-image: linear-gradient(45deg, blue, green);

Syntax for Color Stops

Color stops define where specific colors begin, end, or transition along the gradient line. A color stop consists of a color value followed by an optional position specified in percentages (%) or length units (px, rem, etc.).

background-image: linear-gradient(to right, red 20%, yellow 50%, green 80%);

In this example:

  • Pure red extends from 0% to 20%.
  • The transition from red to yellow occurs between 20% and 50%.
  • The transition from yellow to green occurs between 50% and 80%.
  • Pure green continues from 80% to 100%.

If no positions are specified, the browser spaces the color stops evenly along the gradient line.

Interpolation Hints (Midpoints)

You can adjust the midpoint of a transition between two color stops by placing a unitless percentage value between them without a color declaration.

background-image: linear-gradient(to right, red, 80%, blue);

This shifts the 50/50 blend between red and blue to the 80% mark, causing the gradient to stay red longer before rapidly shifting to blue.

Sharp Lines with Hard Stops

To create distinct stripes instead of smooth blends, set adjacent color stops to the same position:

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

Double-Position Syntax

Modern CSS allows you to declare two positions for a single color stop directly, reducing repetition:

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

This renders a solid block of red across the first half of the element and a solid block of blue across the second half, with a sharp boundary at the 50% line.