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

Set a background image with CSS on the element that should display it. Put the image URL in background-image, then choose how it scales, repeats and aligns. A reliable hero section usually needs background-size: cover, background-position: center, background-repeat: no-repeat and a fallback background-color.

Set a background image: the complete example

HTML provides the element; CSS supplies the decorative background. Keep the text or controls inside the element so they remain real, selectable HTML.

<section class="hero">
  <div class="hero__content">
    <p class="eyebrow">Summer collection</p>
    <h1>Explore the coast</h1>
    <p>Lightweight gear for long days outside.</p>
    <a class="button" href="/shop">Shop now</a>
  </div>
</section>
.hero {
  min-height: 28rem;
  padding: 4rem 2rem;
  display: grid;
  place-items: center;
  color: #fff;
  background-color: #222;
  background-image: url("images/coast.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.hero__content {
  max-width: 42rem;
  text-align: center;
}

The URL is resolved from the stylesheet location. If this CSS is in css/site.css, url("images/coast.jpg") points to css/images/coast.jpg, not the HTML file’s folder. Use ../images/coast.jpg when the image is one directory above the stylesheet, or an absolute path such as /images/coast.jpg when your site is served from the domain root.

Give the element a visible area

A background does not create content or intrinsic height. An empty div with no dimensions can therefore appear to have no image. Add content, padding, a fixed or minimum height, or an aspect ratio.

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

Fixed or minimum height

.banner {
  min-height: 20rem;
  background: url("../images/banner.webp") center / cover no-repeat #16324f;
}

Aspect-ratio box

.card-image {
  aspect-ratio: 16 / 9;
  background: url("images/card.jpg") center / cover no-repeat #eee;
}

Use min-height when text length can change. An aspect ratio is useful for a media tile whose dimensions should follow its width.

Choose between cover and contain

Value What it does Choose it when Trade-off
cover Scales the image until the entire positioning area is covered while preserving proportions. You want a filled hero, banner or card. Parts of the image can be cropped when image and element proportions differ.
contain Scales the complete image to fit inside the area without stretching. The entire diagram, product or illustration must remain visible. Unused space can remain; without no-repeat, the image may tile.
auto Uses the image’s intrinsic dimensions, subject to the positioning area. You need its natural scale and understand overflow. It may not fill the box or may repeat.
.product-card {
  min-height: 18rem;
  background-image: url("images/product.png");
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  background-color: #f4f4f4;
}

With contain, always decide whether repetition is acceptable. For a single illustration, explicitly set background-repeat: no-repeat.

Control the focal point with background-position

center centers the image in both directions. You can use keywords, percentages, lengths or edge offsets.

.hero { background-position: 70% 40%; }
/* Keep a face near the top-right edge */
.profile-hero { background-position: right 2rem top 20%; }
/* Explicit horizontal and vertical lengths */
.map { background-position: 12px 30px; }

The first value is horizontal and the second vertical. With cover, move the position toward the subject that would otherwise be cropped. Test narrow and wide viewports; a focal point that works on desktop can cut off the subject on a phone.

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

Prevent repetition and provide a fallback color

The initial repeat behavior is repeating, so a single background should normally declare no-repeat. Set a color underneath it for transparent pixels, slow connections and failed image requests.

.feature {
  background-color: #222;
  background-image: url("images/feature.jpg");
  background-repeat: no-repeat;
}

The color is also useful when an overlay or a transparent PNG is part of the design.

Use the background shorthand safely

The shorthand combines color, image, position, size, repeat, attachment, origin and clipping. Put the size after the position with a slash.

.hero {
  background: url("images/hero.jpg") center / cover no-repeat #222;
}

Any value omitted from the shorthand returns to its initial value. If a behavior matters, write it explicitly or use longhand declarations. For example, omitting no-repeat can restore repeating, and omitting a color can remove your fallback.

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.

Layer gradients, textures and multiple images

Background layers are comma-separated. The first layer is painted on top of later layers, so put an overlay gradient before the photo.

.hero {
  background:
    linear-gradient(90deg, rgba(0, 0, 0, .72), rgba(0, 0, 0, .08)),
    url("images/hero.jpg") center / cover no-repeat,
    #222;
}

You can also provide multiple image layers with separate longhand values:

Rank #3
CSS Cookbook, 2nd Edition
  • Used Book in Good Condition
.pattern {
  background-image: url("images/noise.png"), url("images/paper.jpg");
  background-position: center, center;
  background-size: auto, cover;
  background-repeat: repeat, no-repeat;
  background-color: #faf7ef;
}

Keep the number of position, size and repeat values aligned with the image layers. A final color is painted below all image layers.

Make backgrounds responsive

Change the crop or focal point at a breakpoint

.hero {
  min-height: 30rem;
  background-position: 65% center;
}

@media (max-width:  fortyrem) {
  .hero {
    min-height: 24rem;
    padding: 3rem 1.25rem;
    background-position: 58% center;
  }
}

Replace fortyrem with a valid CSS length such as 40rem; the example is shown this way to make the breakpoint easy to notice. A production rule must use the valid form:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
@media (max-width: 40rem) {
  .hero { background-position: 58% center; }
}

Serve different assets

When mobile and desktop need genuinely different crops, use media queries with separate URLs or use a responsive HTML image for meaningful content. CSS backgrounds are best for decoration; they are not a replacement for an informative image with an appropriate text alternative.

Respect reduced motion

A static background has no motion requirement. If you add animated background positioning or transitions, wrap those effects in a prefers-reduced-motion media query and provide a non-animated state.

Background image or <img>?

Use a background for visual decoration behind content: a texture, color field or hero photograph that does not carry information the reader needs. Use an HTML <img> when the image is content, such as a product photo, chart, diagram or news image. Give informative images meaningful alternative text through the HTML image’s alt attribute. A CSS background alone has no equivalent place for that text alternative, so do not hide essential information in it.

Keep headings, links and buttons as HTML over the background. Check contrast against every crop and state; a dark overlay gradient can help, but verify the actual text at the smallest viewport.

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

Useful background properties

Property Purpose Example
background-image Sets one or more images or gradients. url("hero.jpg")
background-color Paints the fallback and the area below transparent layers. #222
background-size Controls scaling. cover, contain, auto
background-position Places the image in the positioning area. center top
background-repeat Controls tiling. no-repeat, repeat-x
background-attachment Controls how the background relates to scrolling. scroll (the normal behavior)
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot a missing or incorrect background

Nothing appears

  • Inspect the element and confirm the selector matches its class or ID.
  • Check the computed background-image value in developer tools.
  • Open the image URL directly and inspect the Network panel for a 404, blocked request or incorrect MIME response.
  • Recalculate the relative path from the CSS file, not from the HTML file.
  • Give the element content, padding, height, min-height or aspect-ratio.
  • Look for a later rule or shorthand that overrides the declaration.

The image is tiled

Set background-repeat: no-repeat. If you use contain, this is especially important because the image may leave unused space.

The subject is cropped

cover necessarily crops when proportions differ. Try a new background-position, use a less tightly framed source, adjust the element’s aspect ratio, or switch to contain when showing the whole image matters more than filling the box.

The image is stretched or distorted

Background sizing should preserve proportions with cover, contain or auto. Avoid treating width and height as independent background dimensions unless you intentionally use two values, and do not confuse a background with an absolutely positioned <img>.

Text is hard to read

Add an overlay layer, choose a different focal point, or use a fallback color that works before the image loads. Recheck every responsive crop and keyboard-focus state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
CSS Cookbook
  • Used Book in Good Condition

Or skip the browser setup

If you need rendered screenshots rather than a local visual check, ScreenshotNeo returns a PNG, JPEG, WebP or PDF from one request. It accepts the page like a visitor first, removes cookie-consent banners, newsletter popups and chat widgets, and reports whether the page was cleanly captured. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed.

Example request (the API can capture the page after your CSS is deployed):

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

See the ScreenshotNeo documentation for all options, including viewport and device presets, full-page lazy-image loading, CSS selectors, dark mode, retina scale, PDF paper settings, custom CSS and JavaScript, clicks, waits, blocked resources, headers, cookies, user agents, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous webhooks, bulk capture and usage reporting. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

The Free plan includes 1,000 shots each month without a card. Starter is $5 for 3,000 shots; Growth $15 for 15,000; Pro $39 for 60,000; Scale $99 for 250,000; and Business $249 for 1,000,000. Yearly billing gives two months free, and every feature is included on every plan. Create a free ScreenshotNeo account to try it.

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

Validate the result before shipping

  1. Load the page with the browser cache disabled and confirm the fallback color appears briefly without causing a layout collapse.
  2. Test the image URL, stylesheet URL and production base path, not only a local file URL.
  3. Resize from a wide desktop viewport to a narrow phone viewport and adjust the focal point where needed.
  4. Check that important text remains readable over the darkest and lightest image areas.
  5. Confirm that decorative backgrounds are not the only place essential information is conveyed.
  6. Inspect the page in a clean session so consent dialogs, overlays or extensions do not hide the result.

Frequently Asked Questions

Can I set a background image directly in the HTML tag?

Yes, with an inline style such as <div style="background-image: url('images/hero.jpg')">, but a stylesheet is easier to reuse, override and maintain.

Why does my background image not make the div taller?

Backgrounds do not contribute intrinsic content size. Add content, padding, a height, a minimum height or an aspect ratio.

How do I stop a background image from repeating?

Declare background-repeat: no-repeat, or include no-repeat in the background shorthand.

Which format should I use for a CSS background?

Choose an image format supported by your target browsers and appropriate for the asset; the CSS behavior is independent of whether the URL points to PNG, JPEG, WebP or another supported format.

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

Quick Recap

SaleBestseller No. 1
Bestseller No. 3
CSS Cookbook, 2nd Edition
CSS Cookbook, 2nd Edition
Used Book in Good Condition
$6.24
SaleBestseller No. 4
Bestseller No. 5
CSS Cookbook
CSS Cookbook
Used Book in Good Condition
$110.78

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.