Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put the background on the element whose content should appear in front of the image, then give that element visible height and choose how the image fits. This dependable starting point fills a hero section without distortion:

<section class="hero">
  <h1>Welcome</h1>
</section>
.hero {
  min-height: 24rem;
  background-image: url("images/hero.jpg");
  background-color: #333;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

The HTML supplies the box; CSS paints the image behind its contents. Replace the path with an image URL that is valid from the location of your CSS file.

What a CSS background image does

A CSS background is painted inside an element’s background area and does not become a separate child node. It is useful for decorative photographs, textures, and visual atmosphere behind headings or controls. The element still needs content, padding, a defined height, or a minimum height; an empty element with no dimensions has no visible area to paint.

For a page-wide background, apply the declaration to body (and ensure the page has the height you intend). A small element’s background paints only that element’s box, not the entire viewport.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Choose the image fit before writing the final CSS

The box and source image rarely have the same aspect ratio. Pick the behavior that matches the design rather than relying on defaults.

Setting What it does Use it when Trade-off
cover Scales proportionally until the entire box is filled. A hero or card must have no uncovered area. Edges can be cropped.
contain Scales proportionally so the complete image fits inside the box. The whole source must remain visible. Empty space can remain; explicitly disable tiling.
Explicit size Sets a deliberate rendered width and height. You have a controlled design and accept fixed dimensions. Independent dimensions can distort the image.

Cover a section

background-size: cover is the usual choice for a banner. It preserves proportions, but a narrow phone viewport may crop the left and right edges (or the top and bottom, depending on the ratios). Use background-position to keep the important subject visible:

.hero {
  min-height: 24rem;
  background-image: url("images/hero.jpg");
  background-size: cover;
  background-position: center top;
  background-repeat: no-repeat;
}

Useful positions include center, top, bottom, left, right, and percentage or length pairs such as 70% center. Inspect both narrow and wide layouts; the focal point that works on desktop may be cropped on mobile.

Show the complete image

Use contain when cropping would remove meaning, such as a diagram or product image. Add no-repeat, because background images repeat by default:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.diagram {
  min-height: 20rem;
  background-color: #f2f2f2;
  background-image: url("images/diagram.png");
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
}

The fallback color fills the unused space and remains visible if the image cannot load.

Use the background shorthand

The longhand declarations are easiest to debug. Once the values are settled, this equivalent shorthand is compact:

.hero {
  min-height: 24rem;
  background: url("images/hero.jpg") center / cover no-repeat #333;
}

In shorthand, place background-size after background-position, separated by a slash. Put the fallback color at the end.

Add a readable overlay with multiple backgrounds

Text over a photograph can become unreadable wherever the image is bright. CSS lets you stack a gradient above the photograph. The first listed layer is on top:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.hero {
  min-height: 24rem;
  background-image:
    linear-gradient(rgb(0 0 0 / 45%), rgb(0 0 0 / 45%)),
    url("images/hero.jpg");
  background-position: center, center;
  background-repeat: no-repeat, no-repeat;
  background-size: cover, cover;
  color: white;
}

Values map by comma position: the first position, repeat value, and size belong to the gradient; the second belongs to the photo. If a property has fewer comma-separated values than layers, the shorter list repeats. You can use a directional gradient instead of a uniform overlay when text sits on one side.

Make the layout responsive

Give the box flexible height

A fixed height can work for a controlled banner, but text wrapping and localization may require more room. Combine padding with a minimum height:

.hero {
  min-height: 18rem;
  padding: 4rem 1.5rem;
  display: grid;
  align-content: center;
  background: url("images/hero.jpg") center / cover no-repeat #333;
}

The content determines additional height when needed, while the minimum keeps a short hero visible.

Change the focal point at a breakpoint

If the subject moves out of the crop on small screens, change its position rather than stretching the image:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.hero {
  background-position: 65% center;
}

@media (max-width: 40rem) {
  .hero {
    min-height: 28rem;
    background-position: 80% center;
  }
}

Choose percentages by looking at the actual crop. There is no universally correct focal coordinate.

Background image versus an HTML image

Use a background for decoration that supports the surrounding content. Background images are not exposed as image content to screen readers. MDN states: “Browsers do not provide any special information about background images to assistive technology.” See the MDN background-image reference.

If the picture communicates information, put it in the document as an HTML <img> with suitable alternative text, or provide the same information in nearby text. Do not hide an essential chart, instruction, or product detail in CSS alone.

Check contrast over the real crop

Text must remain readable at every viewport and crop position, including when the image fails. WCAG thresholds referenced by MDN are 4.5:1 for ordinary text and 3:1 for large text; MDN defines large text there as at least 24px, or bold 18.66px. Verify the rendered text against the photograph and overlay, not just against a color swatch. A solid background-color is a useful failure fallback.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common implementation patterns

Full-page background

body {
  margin: 0;
  min-height: 100vh;
  background-color: #18202a;
  background-image: url("images/site-background.jpg");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

A background on body is commonly propagated to the root element under normal transparent-root conditions. If you need a page section with independent scrolling or layering, put the background on that section instead.

One background image on a card

.card {
  min-height: 16rem;
  padding: 1.5rem;
  background: url("images/card.jpg") center / cover no-repeat #555;
}

Texture that should tile

.pattern {
  background-color: #eee;
  background-image: url("images/noise.png");
  background-repeat: repeat;
}

Tiling is the default behavior and can be desirable for small textures. It is usually surprising for a photographic hero, so set no-repeat there.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Debug a missing or wrong background

  1. Verify the path. A relative URL is resolved from the CSS file, not from the HTML file. Check capitalization, extension, and folder nesting. Test an absolute URL only when that resource is intentionally public.
  2. Confirm the element has dimensions. Inspect it in browser developer tools. Add content, padding, height, or min-height and check for a parent that collapses.
  3. Look for an overriding rule. A later background shorthand can reset earlier longhands. Inspect the computed background-image, size, position, and repeat values.
  4. Stop accidental tiling. Set background-repeat: no-repeat for a single image.
  5. Reconsider the fit. With cover, cropping is expected; with contain, empty space is expected. Switch only if that behavior is wrong for the design.
  6. Move the focal point. Adjust background-position after checking the narrowest and widest layouts.
  7. Check loading and fallback. Network errors, blocked requests, unsupported formats, or a wrong MIME setup can leave only the color. Keep a useful fallback color and inspect the browser network panel.
  8. Separate content from decoration. If users need the image’s information, move that content into HTML and supply an alternative text or description.

Performance and maintainability considerations

Large photographic backgrounds can delay visual loading and consume mobile data. Resize and compress the source for its largest intended display, avoid using a multi-megapixel original when a smaller asset is sufficient, and keep decorative backgrounds out of critical content when they are not needed. Test the actual page at slow connections and on high-density screens.

Keep image URLs predictable and version assets when replacing them so stale caches do not preserve an old design. If the image is optional, the fallback color should still produce a coherent layout. Use CSS custom properties when several components share a theme:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
:root {
  --hero-image: url("images/hero.jpg");
}

.hero {
  background: var(--hero-image) center / cover no-repeat #333;
}

Or skip the browser setup

If your goal is to obtain a rendered screenshot of a page that uses CSS backgrounds, ScreenshotNeo can capture the URL through one request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo documentation for options such as full-page capture, lazy-image loading, CSS selectors, viewport and device presets, retina scale, custom CSS or JavaScript, waits, headers, cookies, geolocation, caching, PDFs, signed links, asynchronous jobs, webhooks, and bulk capture. The Free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

FAQ

Why is my background image repeating?

Repeating is the CSS default. Add background-repeat: no-repeat for a single hero or photograph.

Can I use more than one background image?

Yes. Separate layers with commas; the first layer is painted above later layers. A gradient-over-photo combination is a common example.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does cover cut off my subject?

cover fills the box while preserving proportions, so mismatched aspect ratios require cropping. Adjust background-position, alter the box ratio, or use contain if the complete image is more important.

Should a meaningful image be a background?

No. Put meaningful content in an HTML image with appropriate alternative text or an equivalent description; assistive technology does not receive special information from CSS backgrounds.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.