Set a CSS background with background-image: url('/images/photo.jpg'); on the element you want to decorate. Give that element a visible area, then choose background-size: cover to fill it (with possible cropping) or contain to keep the entire image visible. Add background-position, background-repeat: no-repeat, and a fallback background-color for a dependable result.
The basic background-image rule
The background-image property attaches one or more images to an element. It does not create height by itself. If the element has no content, padding, height, or minimum height, there may be no box in which the image can appear.
.hero {
min-height: 24rem;
background-color: #243044;
background-image: url('/images/hero.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
Apply the class to an element in your HTML:
<section class="hero">
<h1>Product launch</h1>
<p>A short message over the image.</p>
</section>
The URL is resolved by the browser. A leading slash points to the site root; a relative URL such as ../images/hero.jpg is resolved relative to the CSS file. Confirm the final URL opens directly and that filename capitalization matches the server.
Choose cover, contain, or the natural image size
The background-size property controls how the image fits the element’s background positioning area.
#1 Best Overall
- HTML CSS Design and Build Web Sites
- Comes with secure packaging
- It can be a gift option
| Value | What it does | Use it when | Trade-off |
|---|---|---|---|
cover |
Scales the image until both dimensions cover the box while preserving its proportions. | A hero, banner, or card must be filled edge to edge. | Parts of the image can be cropped. |
contain |
Scales the complete image to fit inside the box without distortion. | The whole illustration, logo, or diagram must remain visible. | Unused space can remain; disable tiling with no-repeat. |
auto |
Uses the image’s intrinsic dimensions (subject to positioning and repetition). | You intentionally want the source size or a tiled texture. | It may not fill the element or may repeat. |
| Explicit length or percentage | Sets a custom background width and height, such as 100% auto. |
You need a deliberate crop or scale different from the presets. | Independent width and height values can distort the image. |
With cover, cropping is expected. Keep the important subject in view by changing background-position:
.hero {
background-size: cover;
background-position: center top;
}
.product-card {
background-size: cover;
background-position: 70% 20%;
}
Keywords such as center, top, and right are convenient; percentages let you tune the focal point. If showing every pixel is more important than filling the box, switch to contain and select a suitable background color for the remaining space.
Prevent tiling and provide a fallback color
Images repeat by default in the background painting area. Set background-repeat: no-repeat for a single photograph or illustration. A color underneath remains useful if the image is slow to load or fails. MDN recommends specifying a background color even when an image normally covers it; see the background-image reference.
.panel {
min-height: 18rem;
background-color: #18202c;
background-image: url('/images/panel.webp');
background-repeat: no-repeat;
background-position: center;
background-size: contain;
}
For a deliberate repeating texture, choose the axis explicitly instead:
Recommended Free Tools
.stripe {
background-image: url('/images/stripe.svg');
background-repeat: repeat-x;
background-position: left top;
}
Use the background shorthand carefully
The background shorthand can set color, image, position, size, and repetition in one declaration:
.hero {
background: #243044 url('/images/hero.jpg') center / cover no-repeat;
}
The slash separates position from size. Shorthand declarations reset omitted background subproperties to their initial values, so a later shorthand can unexpectedly undo a setting from an earlier rule. Use longhand declarations when clarity or incremental overrides matter.
Rank #2
Layer gradients, photos, and other backgrounds
Background layers are comma-separated. The first image is closest to the user, so a gradient can sit above a photograph and improve text legibility:
.hero {
min-height: 24rem;
background-color: #243044;
background-image:
linear-gradient(rgb(0 0 0 / 45%), rgb(0 0 0 / 45%)),
url('/images/hero.jpg');
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
Each layer may have its own position, size, and repeat value. The fallback color is still painted beneath the layers if the image request fails.
Make a background fill the page without surprises
Attach a page background to body when it should follow the document’s height:
html, body {
min-height: 100%;
}
body {
margin: 0;
background-color: #101722;
background-image: url('/images/site-background.jpg');
background-position: center top;
background-repeat: no-repeat;
background-size: cover;
}
A viewport-height hero is a different requirement. Use a minimum height based on the viewport while allowing content to expand:
.landing-hero {
min-height: 100svh;
padding: 4rem 1.5rem;
box-sizing: border-box;
background: #243044 url('/images/landing.jpg') center / cover no-repeat;
}
The image follows the element’s box and its background behavior; it is not automatically a fixed wallpaper. Keep the target element’s padding, content, and overflow in mind when deciding how much of the image should be visible.
Responsive backgrounds and high-density screens
One source crop rarely suits every viewport. A wide desktop hero may leave the subject off-screen on a narrow phone. Media queries can select a different asset or focal point:
Rank #3
.hero {
min-height: 22rem;
background-image: url('/images/hero-wide.jpg');
background-position: center;
background-size: cover;
}
@media (max-width: fortyrem) {
.hero {
background-image: url('/images/hero-tall.jpg');
background-position: 60% center;
}
}
Replace fortyrem with a valid numeric value such as 40rem; it is written out here only to make the unit easy to notice. For density-specific decorative assets, image-set() can offer alternatives:
.logo-backdrop {
background-image: image-set(
url('/images/backdrop.png') 1x,
url('/images/[email protected]') 2x
);
background-repeat: no-repeat;
background-size: contain;
}
For responsive-image guidance, see web.dev’s responsive images lesson. If the image communicates information rather than decoration, prefer semantic HTML with <picture>, <img>, and srcset; those mechanisms provide content alternatives and text alternatives.
Accessibility: know when not to use a CSS background
Assistive technology does not receive special information about CSS background images. A screen reader will not announce a background as an image, so do not put essential words, data, or instructions only in the background. Add an HTML image with appropriate alternative text when the visual is meaningful; the web.dev images guide explains the content-image approach.
Text over a photo must remain readable across the entire area where it can appear. MDN’s guidance uses a contrast ratio of at least 4.5:1 for body text and 3:1 for larger text (at least 24px, or bold text at least 18.66px). Measure the actual rendered text against the lightest and darkest parts of the image. A dark or light gradient, a solid text panel, or a different focal crop can help, but verify the result rather than assuming an overlay is sufficient.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Complete patterns you can adapt
Hero with a readable overlay
.hero {
display: grid;
align-items: end;
min-height: 28rem;
padding: 2rem;
color: white;
background-color: #1d2735;
background-image:
linear-gradient(180deg, rgb(0 0 0 / 5%), rgb(0 0 0 / 75%)),
url('/images/mountain.jpg');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
.hero h1,
.hero p {
max-width: 38rem;
}
Card that keeps an illustration complete
.feature-card {
min-height: 16rem;
padding: 1.5rem;
background-color: #f1f4f8;
background-image: url('/images/diagram.svg');
background-repeat: no-repeat;
background-position: right 1rem bottom 1rem;
background-size: contain;
}
Troubleshoot a missing or incorrect background
- Nothing appears: inspect the element and confirm the rule is applied. Check that it has content, padding, a height, or a minimum height. Open the resolved image URL directly and look for a 404, mixed-content block, or a case mismatch.
- The image tiles: add
background-repeat: no-repeat, or select an intentional axis such asrepeat-x. - The subject is cut off: that is normal for
cover. Adjustbackground-position, use a crop designed for the container, or choosecontainwhen the complete image matters. - There are blank bands:
containpreserves the whole aspect ratio and can leave space. Set a suitablebackground-coloror usecoverif cropping is acceptable. - The image looks distorted: avoid forcing unrelated width and height values. Use
cover,contain, or one explicit dimension with the other set toauto. - A newer rule has no effect: search for a later
backgroundshorthand, a more-specific selector, or an inline style that resets your longhand properties. - Text is difficult to read: test contrast over the actual image, then strengthen the gradient, add a backing panel, reposition the text, or choose another asset.
- The visual carries meaning: move it into the HTML as an image with alternative text instead of relying on a CSS background.
Or skip the browser setup
If you need a screenshot of the finished page rather than a local browser workflow, ScreenshotNeo can return a PNG, JPEG, WebP, or PDF from one GET request. Its cleanup steps accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. It also provides an MCP server for AI agents, with take_screenshot, get_page_info, and capture_pdf tools.
For the full parameter list, see the ScreenshotNeo API documentation. This cURL request captures a page as WebP:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Equivalent 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)
Equivalent 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 screenshots a month with no card. Paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account to try it.
Rank #4
Frequently asked questions
Can I use a CSS background instead of an img element?
Yes, when the image is decorative. Use an HTML image with alternative text when the visual conveys information or meaning.
Free tools Windows power users keep installed
One-click scans. No signup required.
Why does cover crop my image?
cover preserves the aspect ratio while filling the entire box, so a mismatch between image and box proportions necessarily removes some edges. Change the focal position or use contain.
How do I change the focal point?
Set background-position with keywords or percentages, for example background-position: 70% 20%.
Is the shorthand safe to use?
Yes, provided you remember that omitted background subproperties reset to their initial values. Use longhand declarations when you need predictable overrides.
Frequently Asked Questions
Can a background image have alt text?
No. CSS backgrounds are not exposed as image content to assistive technology. Put meaningful imagery in an HTML img or picture element and provide appropriate alternative text.
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 & 11What should I use for a logo that must remain fully visible?
Use background-size: contain with background-repeat: no-repeat, or use an HTML image when the logo is content rather than decoration.
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.

