Skip to content
AgileLogics
6 min read

Backgrounds, Gradients, and Shadows

Prerequisites: Colors, The box model

Background colors and images

.hero {
  background-color: #1d3557;
  background-image: url("/img/pattern.svg");
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}
  • background-size: cover scales the image to fill the box (cropping if needed); contain fits the whole image inside it.
  • background-position accepts keywords (top right) or lengths.
  • The URL in url() is relative to the stylesheet, not the page.
  • Always set a background-color behind a background image, so text stays readable while the image loads (or if it fails).
  • Background images are decoration: they have no alt text. Content images belong in img elements.

The background shorthand combines them:

.hero { background: #1d3557 url("/img/pattern.svg") center / cover no-repeat; }

Gradients

Gradients are generated images, so they go in background-image:

.sunset { background-image: linear-gradient(to bottom, #ff7e5f, #feb47b); }
.diagonal { background-image: linear-gradient(135deg, teal 0%, navy 100%); }
.spotlight { background-image: radial-gradient(circle at top, #fff 0%, #ddd 70%); }
.pie { background-image: conic-gradient(tomato 0 40%, gold 40% 75%, teal 75%); border-radius: 50%; }
.stripes { background-image: repeating-linear-gradient(45deg, #eee 0 10px, #fff 10px 20px); }

Two color stops at the same position create a hard edge — that's how the pie chart and the stripes work.

Multiple backgrounds

Layers are listed front to back:

.banner {
  background:
    linear-gradient(rgb(0 0 0 / 60%), rgb(0 0 0 / 20%)),
    url("/img/bakery.jpg") center / cover;
  color: white;
}

The dark gradient over the photo keeps white text readable.

Shadows

.card { box-shadow: 0 2px 8px rgb(0 0 0 / 12%); }
.card:hover { box-shadow: 0 8px 24px rgb(0 0 0 / 18%); }
.inset { box-shadow: inset 0 2px 4px rgb(0 0 0 / 15%); }
.ring { box-shadow: 0 0 0 3px hsl(210 90% 60%); }

box-shadow takes x-offset, y-offset, blur, optional spread, and color. Soft, low-opacity shadows look more natural than dark ones. Several shadows can be comma-separated. text-shadow works similarly for text, and filter: drop-shadow() follows the shape of transparent images.

Practice

Create a .badge-new with a left-to-right gradient from gold to orange, rounded corners, and a subtle shadow.

Show solution
.badge-new {
  background-image: linear-gradient(to right, gold, orange);
  border-radius: 6px;
  padding: 0.25rem 0.5rem;
  box-shadow: 0 1px 3px rgb(0 0 0 / 20%);
}