OnlineCBT Logo OnlineCBT
CSS Tutorial
CSS · LESSON 12

Background Color, Images, and Gradients

By Ratan Updated: 15 Oct 2026

Apply background images, linear/radial gradients, and control repeat, position, and sizing.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Paint a background without replacing content

A background can contain a color, one or more images, and gradients. Background images are decorative: they do not provide an HTML alt attribute. Put meaningful diagrams or product images in the document with appropriate alternatives instead.

.hero {
  color: white;
  background-color: #172554;
  background-image:
    linear-gradient(rgb(15 23 42 / 0.8), rgb(15 23 42 / 0.5)),
    url("images/study-room.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  padding: 4rem 1.5rem;
}

The first listed background is painted above later ones. The gradient darkens the photo so white text has a better chance of remaining legible. Still inspect actual contrast; an overlay does not prove every image works. The fallback color remains useful while the image loads or if it fails.

Cover versus contain

cover fills the box and may crop the image. contain fits the whole image and may leave unused space. Neither changes the element's dimensions by itself. Give the container useful content or an explicit sizing rule; a background image alone does not create intrinsic content height.

Gradient experiment

.banner {
  background: linear-gradient(120deg, #172554, #1d4ed8);
}
.spotlight {
  background: radial-gradient(circle at top left, #dbeafe, #ffffff);
}

A gradient is an image generated by CSS. Its direction, stops and shape determine how colors blend. Keep important text readable across the entire painted area.

Path and shorthand pitfalls

In an external stylesheet, a relative image URL resolves relative to that CSS file's URL. A later background shorthand can reset image, position or repeat values. Inspect computed styles and the Network panel before changing unrelated layout rules.

Practice

  1. Switch cover to contain and compare cropping.
  2. Temporarily break the image path and ensure the fallback remains readable.
  3. Move meaningful instructional text out of a background image into real HTML.
  4. Test narrow and wide viewports, because background cropping changes with aspect ratio.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat