Lesson 6 — Styling

Backgrounds and Borders

Background and border properties let you add colour, images, and shape to the edges and fill of an element's box.

Background Properties

A background can be a solid colour, an image, or both layered together. The shorthand background property combines several individual properties in one line.

CSS — Backgrounds and borders
.hero {
    background-color: #0a0a0a;
    background-image: url('pattern.svg');
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
}

.card {
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

Common Mistakes

  • Forgetting background-size: cover when a background image should fill its container without distortion.
  • Setting a border-radius on a container without also setting overflow: hidden when a child image needs to be clipped to match the rounded corners.
  • Using too many box-shadow layers, which hurts rendering performance on lower-end devices.
  • Not providing a fallback background-color for when an image fails to load or is still loading.

Professional Tip

Always pair a background-image with a similar background-color as a fallback. It prevents an awkward flash of unstyled content while the image loads, and keeps text readable if the image request fails.

Your Turn

Build a hero banner section with a dark background colour, a subtle background image, rounded corners on a card floating in front of it, and a soft box-shadow.

Mini Quiz

Which background-size value makes an image fill its container completely while preserving its aspect ratio (possibly cropping it)?