CodeBlanks Logo Icon CodeBlanks

Linear gradient

CSS course · Advanced · Lesson 7/52

Learn linear gradients with linear-gradient().

What is a linear gradient?

A linear gradient blends two or more colors smoothly along a straight line. In CSS you write it with the linear-gradient() function. The simplest form is linear-gradient(blue, white) — blue at the top, fading into white below.

Gradients are used as backgrounds: background: linear-gradient(blue, white); is enough. You hand it a list of colors instead of one value, and the browser draws the blend.

Setting the direction

You give the gradient its direction as the first argument. With keywords: to top, to right, to bottom left. to top means the colors run from bottom to top.

For finer control, use an angle: 45deg, 90deg, 180deg. 0deg points up, 90deg right, 180deg down. Angles are measured counter-clockwise.

Color stops

Each color you add to a gradient is a color stop. By default, stops are spaced evenly: with two colors the blend sits in the middle, with three colors at one-third intervals.

To set a stop's position explicitly, write a percentage after the color, like blue 20%. This tells blue to start at the 20% mark. The blend stays smooth; only the start point shifts.

Exercise Add a linear gradient to the hero background

Define a background for the .hero selector. The value must be a linear-gradient() function with to right as the direction and navy and teal as colors. Use only the background property.

Show example solution
/* add gradient to hero background */
.hero {
  background: linear-gradient(to right, navy, teal);
}

Test yourself

  1. Which form gives the default (top to bottom) direction?

    background: linear-gradient(blue, white);
    • List only the colors, with no direction
    • Write to top
    • Write to left
    • Write 45deg
    Show answer

    List only the colors, with no direction — Correct. Without a direction, the default is to bottom, top to bottom.

  2. Write the horizontal direction

    background: linear-gradient(____, blue, white);
    Show answer
    background: linear-gradient(to right, blue, white);

All lessons in Advanced