Set the image on the homepage section that should display it—usually a hero container—then define a fallback color, disable tiling, choose how the image is fitted, and position its focal point. A dependable baseline is:
.hero {
background-color: #1f2937;
background-image: url('/images/home-hero.webp');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
This fills the hero edge to edge while keeping the image proportional. The trade-off is that cover can crop the edges when the image and container have different proportions.
Put the background on the element that owns the hero
A CSS background belongs to an element, not to the page in the abstract. Give the homepage section a class and apply the image there:
<header class="hero">
<div class="hero__content">
<p class="eyebrow">Build better products</p>
<h1>A clear headline over a strong visual</h1>
<p>Supporting copy remains readable at every viewport size.</p>
<a class="button" href="/start">Get started</a>
</div>
</header>
Then add the CSS:
.hero {
min-height: 32rem;
display: grid;
place-items: center;
padding: 4rem 1.5rem;
color: #fff;
background-color: #1f2937;
background-image: url('/images/home-hero.webp');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
.hero__content {
width: min(100%, 68rem);
}
The min-height, padding and content give the element a rendered area. A background cannot be seen on an element whose height collapses to zero.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →#1 Best Overall
- HTML CSS Design and Build Web Sites
- Comes with secure packaging
- It can be a gift option
Use a correct image URL
In a stylesheet, a root-relative URL such as /images/home-hero.webp starts at the website’s domain root. A relative URL such as ../images/home-hero.webp is resolved relative to the CSS file’s location. If your stylesheet is at /css/site.css, url('../images/home-hero.webp') points to /images/home-hero.webp. Confirm the final URL directly in a browser and check the Network panel for a 200 response.
Choose cover or contain
The background-size value controls whether the image fills the box or remains completely visible.
| Value | What it does | Best use | Cost |
|---|---|---|---|
cover |
Scales proportionally until both dimensions cover the container; excess image area is cropped. | Photographic heroes and full-bleed banners. | Some edge content may disappear, especially on narrow screens. |
contain |
Scales proportionally so the entire image fits inside the container. | Logos, diagrams, screenshots and artwork where every detail matters. | Leaves empty bands on one or two sides when proportions differ. |
Full-bleed photographic hero
.hero {
background-size: cover;
}
With a wide desktop image in a tall mobile hero, cover enlarges the image until the height is covered, so the left and right edges are cropped. Design the source image with safe space around the subject, or move the focal point with background-position.
Keep the complete artwork visible
.product-illustration {
min-height: 24rem;
background-color: #f3f4f6;
background-image: url('/images/product-diagram.svg');
background-repeat: no-repeat;
background-position: center;
background-size: contain;
}
Expect visible background-color around a contained image. That is intentional, not a loading failure.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Stop repeating and control the focal point
Images repeat by default when they are smaller than the element. Set background-repeat: no-repeat for a single hero image. Set the position explicitly because the default is the top-left corner.
.hero {
background-repeat: no-repeat;
background-position: center center;
}
You can use keywords, percentages or lengths:
/* Keep a face toward the right side of the frame */
.hero {
background-position: 68% center;
}
/* Keep the top of a product visible */
.hero--product {
background-position: center 28%;
}
/* A precise offset, useful for art-directed layouts */
.hero--offset {
background-position: 2rem center;
}
The first value is horizontal and the second vertical. Test the position at the narrowest supported width, not only on a desktop monitor.
Use the shorthand safely
The background shorthand combines color, image, position, size and repeat. When position and size are both present, put a slash between them:
.hero {
background: #1f2937 url('/images/home-hero.webp') center / cover no-repeat;
}
Longhand declarations are easier to debug when you are tuning one property at a time. Shorthand is useful for a final compact rule, but remember that resetting shorthand can also reset other background properties you set elsewhere.
Layer a readable overlay over the image
Hero copy often crosses bright and dark parts of a photograph. A pseudo-element creates a consistent overlay without changing the source file:
.hero {
position: relative;
isolation: isolate;
color: #fff;
background: #1f2937 url('/images/home-hero.webp') center / cover no-repeat;
}
.hero::before {
content: "";
position: absolute;
inset: 0;
z-index: -1;
background: rgb(0 0 0 / 0.42);
}
.hero__content {
position: relative;
}
Alternatively, use a gradient as the first layer and the image as the second:
.hero {
background-image:
linear-gradient(rgb(0 0 0 / 0.48), rgb(0 0 0 / 0.48)),
url('/images/home-hero.webp');
background-position: center, center;
background-size: cover, cover;
background-repeat: no-repeat, no-repeat;
}
Check the final rendered combination. A dark overlay is not automatically accessible if the image remains bright in the text area.
Make the background behave on mobile
There is no separate “mobile background” requirement: cover, an intentional position and a sensible hero height usually suffice. For a different crop or a different file, use a media query:
Rank #3
.hero {
min-height: 34rem;
background-position: 62% center;
}
@media (max-width: fortyrem) {
.hero {
min-height: 28rem;
padding: 3rem 1.25rem;
background-position: 70% center;
}
}
Replace fortyrem with a valid CSS length such as 40rem; it is written out here only to make the breakpoint easy to spot. A production rule is:
@media (max-width: 40rem) {
.hero {
min-height: 28rem;
padding: 3rem 1.25rem;
background-position: 70% center;
}
}
If the mobile crop cannot preserve the subject, provide a mobile-specific asset:
.hero {
background-image: url('/images/home-hero-wide.webp');
}
@media (max-width: 40rem) {
.hero {
background-image: url('/images/home-hero-tall.webp');
}
}
Accessibility: know when a background is the wrong tool
Browsers do not expose special information about CSS background images to assistive technology. If the image communicates essential information—such as a product diagram, warning or meaningful photograph—put it in the document as an img with useful alternative text:
<img src="/images/team.jpg" alt="The support team in the London office">
Use the background for decoration or atmosphere, and keep the meaning in semantic HTML. Decorative images should not force a screen-reader user to infer content that sighted users receive.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsCheck text contrast
For ordinary body text over the rendered image, target a contrast ratio of at least 4.5:1. Large text has a 3:1 threshold. Evaluate the actual crop, overlay and responsive positions with a contrast checker; a color that passes over one part of a photograph can fail over another. A solid or translucent overlay makes the result more stable, but it still needs testing.
Responsive, performance and rendering considerations
Give the browser an appropriate asset
Use a modern format such as WebP when your delivery pipeline supports it, and avoid shipping a multi-megabyte source for a small hero. Compress photographs, choose dimensions that match the largest display size, and provide a mobile crop when art direction matters. CSS backgrounds do not offer the same built-in responsive image selection as img with srcset, so media-query swaps are the practical CSS option.
Rank #4
Decide whether the image should load immediately
A visible above-the-fold hero is normally an important visual and should not be delayed unnecessarily. A background lower on the page can still consume bandwidth when its stylesheet is parsed; consider whether an inline semantic image, component-level loading strategy or a smaller asset better fits the page.
Respect reduced motion and user preferences
A static background does not animate by itself. If you add zoom or parallax effects, provide a reduced-motion alternative:
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11@media (prefers-reduced-motion: reduce) {
.hero {
background-attachment: scroll;
}
}
background-attachment: fixed can perform poorly on some mobile browsers and is not required for a hero. Test it before adopting it.
Common problems and exact fixes
The image is not visible
- Open the URL from
url()directly. Fix spelling, capitalization and the relative path. - Inspect the Network panel. A 404 means the path is wrong; a blocked request can indicate a content-security-policy or cross-origin configuration issue.
- Give the element a height,
min-height, padding or content. An empty element with no dimensions has no area to paint. - Check that another rule is not overriding
background-imageor the shorthand later in the cascade. - Confirm the file format and server MIME configuration are valid.
The image tiles
Add background-repeat: no-repeat. If you intentionally need a pattern, use repeat knowingly and choose a small tile designed for that purpose.
The hero looks stretched
Do not set independent background width and height. Use cover or contain, both of which preserve the image aspect ratio. Stretching usually comes from using an img with conflicting dimensions rather than from a CSS background.
The subject is cropped on phones
That is expected with cover when aspect ratios differ. Move the focal point with a percentage position, reduce the hero’s height, add a mobile-specific image, or switch to contain if showing everything is more important than filling the box.
Best Value
Text becomes unreadable
Measure contrast over the actual image at each breakpoint. Add or strengthen a gradient/overlay, move the text into a calmer part of the image, or use a solid panel behind the copy.
The fallback color never appears
A fallback color is visible only where the image is transparent, fails to load, or does not cover the box. Put background-color in the same rule as the image so a failed request still leaves a deliberate surface.
Or skip the browser setup
If you need a rendered homepage image for documentation, previews or automated checks, ScreenshotNeo returns a screenshot from one request. It accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing, and response headers identify the page verdict and whether it was billed.
The API supports PNG, JPEG, WebP and PDF output, full-page lazy-image loading, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF paper and page controls, custom CSS and JavaScript, pre-capture clicks, hidden selectors, selector/delay/network-idle waits, request and resource blocking, custom headers/cookies/user agents, Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API and an OpenAPI specification. Common screenshot-API parameter names also work when switching.
Use the ScreenshotNeo documentation for authentication and all options. A basic call is:
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}`);
ScreenshotNeo also includes an MCP server with take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. 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 to get started.
Frequently Asked Questions
Can I use more than one background image?
Yes. Separate layers with commas, placing the first image in front. Give each layer its own position, size and repeat value, or use shared values when the same settings fit all layers.
Should a logo be a CSS background?
Usually no. A logo that identifies the brand should be semantic content, commonly an img with an appropriate alternative text, so assistive technology and other user agents can access it.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Why does contain leave blank space?
Contain preserves the entire image and its aspect ratio. When the image and element have different proportions, the unused area is filled by the background color rather than cropped.
Quick Recap
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.

