Chapter 12 of 33

Backgrounds & Gradients

Every box on a web page has a background layer painted behind its content. Hero banners with photos, buttons with colour fades, striped warning bars, even simple pie charts — all of these can be built with CSS backgrounds and gradients, often without a single image file.

In this chapter we will learn how backgrounds are painted, how to control where an image sits and how big it is, how to stack several layers, and how to create linear, radial and conic gradients. You should already know colour formats from Colors and the box layers from The Box Model and Borders & Outlines.


The Background Properties at a Glance

PropertyControlsInitial value
background-colorSolid colour behind everythingtransparent
background-imageImage(s) or gradient(s)none
background-repeatWhether/how the image tilesrepeat
background-positionWhere the image is placed0% 0% (top left)
background-sizeHow big the image is drawnauto (natural size)
background-attachmentWhether it scrolls with the pagescroll
background-originWhich box positioning is measured frompadding-box
background-clipWhich box the background is painted insideborder-box

Backgrounds are not inherited. A child looks like it has its parent's background only because its own background is transparent and you see the parent through it.


background-color

.alert {
  background-color: #fff3cd;
}

.overlay {
  background-color: rgb(0 0 0 / 0.5);   /* 50% transparent black */
}

By default the colour fills the border box — content, padding and the area under the border. You can see this with a dashed border: the colour shows through the gaps between dashes. (We'll change this with background-clip later.)

Always set a background colour when you use light text on a background image. If the image fails to load, the colour keeps the text readable.


background-image

.hero {
  background-image: url("images/mountains.jpg");
}
  • The path inside url() is relative to the CSS file, not to the HTML page. If your stylesheet is in css/style.css and the image in images/, you need url("../images/mountains.jpg").

  • Background images are decoration. They have no alt text and are invisible to screen readers. If the image carries meaning (a product photo, a chart), use an <img> element instead.

  • An element with only a background image and no content has zero height. You must give it a height (or padding, or content) to see the image.


background-repeat

By default, an image smaller than the box is tiled in both directions until it fills the box.

ValueEffect
repeatTile horizontally and vertically (default); edge tiles may be cut off
repeat-xTile only horizontally
repeat-yTile only vertically
no-repeatDraw the image once
spaceRepeat only whole tiles and spread the leftover space between them
roundRepeat whole tiles, stretching or shrinking them slightly so they fit exactly

For photos you almost always want no-repeat; repeating is for patterns and textures.


background-position

background-position takes an x value and a y value. Keywords, lengths and percentages are all allowed:

background-position: center;          /* center center */
background-position: right top;
background-position: 20px 40px;       /* 20px from left, 40px from top */
background-position: right 20px bottom 10px;   /* offsets from the right and bottom edges */

How percentages work (a favourite exam question)

Percentages do not mean "move the image's top-left corner by x% of the box". Instead, the point at x% of the image is lined up with the point at x% of the box. That's why 50% 50% centres the image exactly and 100% 100% puts it in the bottom-right corner.

The formula for the offset of the image's left edge is:

offset = (box size − image size) × percentage

Worked example: a box 400px wide, an image 100px wide, background-position: 25% 0:

offset-x = (400 − 100) × 0.25 = 300 × 0.25 = 75px

The image starts 75px from the left edge. We rendered this in Chrome and measured the image starting exactly 75px in. Note that if the image is larger than the box, (box − image) is negative, so the image moves left/up — which is exactly what you want when centring a big photo.


background-size

ValueMeaning
autoNatural size of the image (default)
200px 100pxExact width and height
50%Width = 50% of the background area; height auto keeps the ratio
coverScale (keeping the ratio) until the box is completely covered; parts of the image may be cropped
containScale (keeping the ratio) until the whole image fits inside; empty space may remain

Worked example: cover vs contain

An image of 400 × 200 is placed in a box of 300 × 300.

Scale needed to match width : 300 / 400 = 0.75
Scale needed to match height: 300 / 200 = 1.5

cover   → use the LARGER scale  (1.5)  → 600 × 300  (fills the box, 300px cropped horizontally)
contain → use the SMALLER scale (0.75) → 300 × 150  (whole image visible, 150px empty vertically)

Chrome draws exactly this: with cover the box is fully filled and the right part of the image is cut off (because the default position is top-left), and with contain the full image sits at the top with empty space below. In practice you pair them with centring:

.hero {
  height: 400px;
  background-image: url("mountains.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

This is the standard "full-width hero image" recipe: the image always fills the banner, whatever the screen size, and the cropping is shared equally on both sides.


background-origin and background-clip

These two properties choose which of the three boxes (border box, padding box, content box) the background relates to:

  • background-origin — where the image's position 0 0 is measured from. Default: padding-box.

  • background-clip — where the background is painted; anything outside is cut away. Default: border-box.

.boxed {
  padding: 20px;
  border: 10px dashed #333333;
  background-color: gold;
  background-clip: content-box;   /* gold only behind the content */
}

With the default border-box, gold fills everything and shows through the dashes. With content-box, the padding and the border area become transparent and only the content area is gold.

Gradient text with background-clip: text

The value text clips the background to the shape of the text itself. Combined with transparent text, it produces gradient-coloured headings:

.gradient-title {
  font-size: 48px;
  font-weight: 900;
  background-image: linear-gradient(90deg, #ff512f, #dd2476);
  -webkit-background-clip: text;   /* for older Chrome/Safari */
  background-clip: text;
  color: transparent;
}

The unprefixed background-clip: text works in current Chrome, Edge, Firefox and Safari; the -webkit- line keeps older versions working. Keep a readable fallback in mind: if the clip isn't supported, transparent text over a gradient box is unreadable.


background-attachment

ValueBehaviour
scrollBackground moves with the element when the page scrolls (default)
fixedBackground is fixed to the viewport; content slides over it (a "parallax-like" effect)
localBackground scrolls with the element's own scrollable content

fixed is ignored by some mobile browsers (notably Safari on iOS), and it can make scrolling slower because the browser repaints more. Use it sparingly.


The background Shorthand

.hero {
  background: #1e293b url("mountains.jpg") center / cover no-repeat;
}

The rules to remember:

  • Order is mostly free, but background-size must come directly after background-position, separated by a slash: center / cover.

  • Any sub-property you don't mention is reset to its initial value. Writing background: red; later in the cascade also wipes out a background-image set earlier.

  • If one <box> value is given (like content-box), it sets both origin and clip; if two are given, the first is origin and the second is clip.


Multiple Backgrounds

An element can have several background layers, separated by commas. The first layer is drawn on top; the colour is always painted at the very bottom.

.banner {
  height: 300px;
  color: white;
  background:
    linear-gradient(rgb(0 0 0 / 0.6), rgb(0 0 0 / 0.6)),   /* layer 1: dark tint (top) */
    url("campus.jpg") center / cover no-repeat;            /* layer 2: photo (below) */
}

The semi-transparent black gradient darkens the photo so white text on it is readable. This "gradient overlay" pattern is extremely common in hero sections. Each sub-property can also take a comma-separated list, one value per layer:

.decor {
  background-image: url("star.svg"), url("dots.png");
  background-position: top right, center;
  background-repeat: no-repeat, repeat;
}

In the shorthand, a background colour is only allowed in the last layer.


Gradients

A CSS gradient is an image generated by the browser that transitions smoothly between two or more colours. Because it is an image, it goes in background-image (or background), not in background-color.

.ok  { background-image: linear-gradient(red, blue); }   /* ✅ */
.bad { background-color: linear-gradient(red, blue); }   /* ❌ invalid, ignored */

Gradients have no natural size, scale perfectly to any resolution, and cost no extra network request. There are three kinds — linear, radial and conic — plus a repeating version of each.


Linear Gradients

linear-gradient(direction, color-stop1, color-stop2, ...)

The default direction is top to bottom (to bottom, which equals 180deg).

.a { background: linear-gradient(#ff7a18, #af002d); }            /* top → bottom */
.b { background: linear-gradient(to right, #ff7a18, #af002d); }   /* left → right */
.c { background: linear-gradient(to bottom right, red, blue); }  /* toward a corner */
.d { background: linear-gradient(45deg, red, blue); }

Angles

Angles in gradients follow a compass, not the maths convention: 0deg points up and angles increase clockwise.

            0deg (to top)
                ↑
270deg  ←       ●       →  90deg (to right)
(to left)       ↓
         180deg (to bottom, the default)

So linear-gradient(0deg, red, blue) starts red at the bottom and ends blue at the top — the gradient line points upward. We checked this in Chrome.

Colour stops

Each colour can have a position. Without positions, stops are spread evenly.

/* red until 20%, fades to blue by 80% */
background: linear-gradient(to right, red 20%, blue 80%);

/* Hard stop: two colours at the same position → sharp edge, no fade */
background: linear-gradient(to right, red 50%, blue 50%);

/* Shorthand for a band: one colour with two positions */
background: linear-gradient(to right, white 0 30%, orange 30% 70%, green 70% 100%);

The last line makes three solid vertical bands, like a flag. Hard stops are the key to drawing stripes and shapes with gradients.

You can also put a lone percentage between two colours, called a colour hint, to move the midpoint of the fade: linear-gradient(red, 20%, blue) reaches the half-way colour at 20% instead of 50%.


Radial Gradients

A radial gradient spreads outward from a centre point.

radial-gradient(shape size at position, color-stops...)
.glow  { background: radial-gradient(yellow, green); }
.spot  { background: radial-gradient(circle at top left, yellow, green); }
.small { background: radial-gradient(circle 50px at center, white, navy); }
  • Shape: ellipse (default, follows the box's proportions) or circle.

  • Size: a length, or a keyword: closest-side, closest-corner, farthest-side, farthest-corner (default). It decides where the last colour stop (100%) is reached.

  • Position: same syntax as background-position; default center.

So radial-gradient(yellow, green) on a 200 × 120 box is an ellipse centred in the box, yellow in the middle and green toward the corners.


Conic Gradients

A conic gradient sweeps colours around a centre point, like the hand of a clock. It starts at the top (12 o'clock) and goes clockwise.

.pie {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: conic-gradient(
    #4caf50 0 40%,     /* 40% green  */
    #2196f3 40% 75%,   /* 35% blue   */
    #ff9800 75%        /* 25% orange */
  );
}

With hard stops, this gives a pie chart: a green slice from 12 o'clock to nearly 5 o'clock (40% of 360° = 144°, and each "hour" on the clock face is 30°, so 144° ≈ 4.8 hours), then blue, then orange back to the top. You can rotate the starting angle and move the centre with conic-gradient(from 90deg at 30% 50%, ...). Conic gradients are also used for colour wheels and loading spinners.


Repeating Gradients

repeating-linear-gradient(), repeating-radial-gradient() and repeating-conic-gradient() repeat the stop pattern forever. The last stop's position defines the length of one repeat.

.warning-stripes {
  background: repeating-linear-gradient(
    45deg,
    #ffd200 0 20px,    /* yellow band 20px wide */
    #222222 20px 40px  /* dark band, then repeat every 40px */
  );
}

This draws diagonal yellow-and-black hazard stripes — no image needed.


Gradient Colour Quality

Two modern details are worth knowing:

  • transparent fades are clean. linear-gradient(red, transparent) fades red to nothing. Very old browsers produced a greyish middle because transparent is "transparent black"; current browsers interpolate in premultiplied colour, so the fade stays red.

  • You can choose the colour space. By default gradients mix colours in sRGB, so blue → yellow passes through a dull grey. Adding a colour space, such as linear-gradient(in oklch to right, blue, yellow), gives a vivid path through cyan and green instead. Interpolation colour spaces are Baseline since 2024 (supported in current Chrome, Edge, Firefox and Safari).

GradientShapeDefault direction / startTypical use
linear-gradientStraight lineTop → bottomButtons, overlays, banners, stripes
radial-gradientEllipse/circle from a pointCentre, outward to farthest cornerGlows, spotlights, vignettes
conic-gradientSweep around a pointFrom 12 o'clock, clockwisePie charts, colour wheels, spinners

Complete Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Backgrounds &amp; Gradients</title>
  <style>
    body {
      margin: 0;
      font-family: system-ui, sans-serif;
      background-color: #f1f5f9;
    }
    .hero {
      padding: 60px 24px;
      color: white;
      text-align: center;
      background:
        radial-gradient(circle at 80% 20%, rgb(255 255 255 / 0.25), transparent 40%),
        linear-gradient(135deg, #4f46e5, #db2777);
    }
    .stats {
      display: flex;
      gap: 24px;
      padding: 24px;
    }
    .pie {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      background: conic-gradient(#22c55e 0 70%, #e2e8f0 70%);
    }
    .bar {
      width: 220px;
      height: 24px;
      border-radius: 12px;
      background: repeating-linear-gradient(45deg, #f59e0b 0 10px, #fbbf24 10px 20px);
    }
  </style>
</head>
<body>
  <section class="hero">
    <h1>GATE 2027 Prep</h1>
    <p>Track your syllabus progress</p>
  </section>
  <div class="stats">
    <div class="pie"></div>
    <div class="bar"></div>
  </div>
</body>
</html>

Result: a hero band that fades diagonally from indigo (top-left) to pink (bottom-right) with a soft white glow near the top-right corner, white centred text, and below it a circular progress chart that is 70% green and 30% light grey, next to a rounded bar with diagonal amber stripes. (The flex layout used for .stats is explained in Flexbox; here it just places the two items side by side.)


Common Mistakes

  • Wrong image path. url() paths are relative to the CSS file, not the HTML file.

  • Background image on an empty element. No content and no height → nothing to see.

  • Gradient in background-color. Gradients are images; the declaration is invalid and ignored.

  • Shorthand overriding. background: blue; written after background-image: url(...) resets the image to none. Use background-color when you only want to change the colour.

  • Forgetting the slash. background: url(a.jpg) center cover; is invalid; it must be center / cover.

  • Thinking 0deg means "to the right". In gradients, 0deg = upward, 90deg = to the right.

  • Meaningful images as backgrounds. Screen readers can't see them; use <img alt="..."> for content.


Interview / Exam Questions

1. What is the difference between background-size: cover and contain?

Both keep the image's aspect ratio. cover scales the image until it covers the whole box (some of the image may be cropped). contain scales it until the whole image fits inside the box (some of the box may stay empty). Mathematically, cover uses the larger of the two scale factors and contain the smaller.

2. A 500px-wide box has a 100px-wide background image with background-position: 50% 0. Where does the image start?

(500 − 100) × 0.5 = 200px from the left, so it is horizontally centred (200 + 100 + 200 = 500).

3. In multiple backgrounds, which layer appears on top?

The first one listed. Later layers are drawn underneath, and the background colour is always painted below all of them.

4. Why can't you write background-color: linear-gradient(...)?

A gradient is an <image> value, not a <color>. It must be used with background-image or the background shorthand (or anywhere else images are accepted, such as border-image).

5. What is the default value of background-clip, and how does it affect a dashed border?

The default is border-box, so the background is painted under the border too and shows through the gaps in a dashed or dotted border. Setting background-clip: padding-box stops it at the inside edge of the border.

6. How do you create sharp colour bands with a gradient?

Use hard stops: give two adjacent colours the same position, for example linear-gradient(to right, red 50%, blue 50%).

7. Which direction does linear-gradient(90deg, red, blue) go?

Left to right: red on the left, blue on the right. 0deg points up and angles go clockwise, so 90deg points to the right.


Summary

  • Backgrounds paint behind content and, by default, under the border too (background-clip: border-box).

  • Control images with background-repeat, background-position and background-size; center / cover + no-repeat is the hero-image recipe.

  • Percentage positions align the same point of image and box: offset = (box − image) × %.

  • Multiple backgrounds are comma-separated; the first is on top.

  • Gradients are images: linear-gradient (default top→bottom, 0deg = up), radial-gradient (from a point), conic-gradient (around a point), and repeating versions.

  • Hard colour stops make stripes, bands and pie charts without image files.

Next, in Text & Fonts, we move from the box to what is inside it: the text.