Backgrounds, borders and shadows

CSS · Essentials · 8 min

These are the everyday properties that turn plain boxes into buttons, cards and banners.

Backgrounds paint behind the content and padding.

  • background-color and background-image, which can be a url() or a gradient: linear-gradient(to right, #6366f1, #ec4899), radial-gradient(...) or conic-gradient(...).
  • background-size: cover fills the box, cropping as needed; contain fits the whole image.
  • background-position: center and background-repeat: no-repeat control placement.
  • Several backgrounds can be layered, separated by commas, with the first on top.

Borders: border: 1px solid #ddd is shorthand for width, style and colour; individual sides use border-top or the logical border-block-start. border-radius rounds corners: 8px for cards, 50% for a circle on a square, 999px for a pill.

Outline looks like a border but takes no space and doesn't affect layout, which is why browsers use it for focus rings. outline-offset moves it out from the edge.

Shadows: box-shadow: 0 4px 12px rgb(0 0 0 / 15%) takes x offset, y offset, blur, optional spread and colour. Add inset for inner shadows and separate several shadows with commas for more realistic depth. text-shadow does the same for text, and filter: drop-shadow() follows the shape of transparent images.

Images that convey content belong in HTML <img> with alt text; CSS backgrounds are for decoration only, because screen readers can't see them.

Example

.card {
  background: white;
  border: 1px solid oklch(90% 0 0);
  border-radius: 12px;
  box-shadow: 0 1px 2px rgb(0 0 0 / 6%), 0 8px 24px rgb(0 0 0 / 8%);
}

.hero {
  background:
    linear-gradient(rgb(0 0 0 / 40%), rgb(0 0 0 / 40%)),  /* dark overlay on top */
    url("/img/hero.jpg") center / cover no-repeat;
  color: white;
}

.avatar { width: 48px; height: 48px; border-radius: 50%; }

button:focus-visible { outline: 3px solid #2563eb; outline-offset: 2px; }

Remember

  • Gradients are background images; layers are comma-separated, first on top
  • border-radius: 50% makes a circle
  • outline doesn't affect layout, which suits focus rings
  • Meaningful images go in HTML, decoration in CSS

Watch out for

  • Removing focus outlines for looks without providing a visible :focus-visible style.

Check yourself

  1. In background: url(a.png), url(b.png), which image is drawn on top?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/background

Builds on

Unlocks

Nothing builds on this yet.