Set a background image with CSS on the element that should display it. Give that element a valid image URL, a visible size, and explicit sizing and positioning rules:
<section class="hero">
<h1>Welcome</h1>
</section>
.hero {
min-height: 320px;
background-image: url("images/hero.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-color: #222;
}
The image is decorative CSS presentation. If an image communicates information that readers need, place it in meaningful HTML with an appropriate text alternative instead of depending on a background alone.
Basic setup: HTML element plus CSS
A background belongs to an element such as a section, header, div, or the page itself. The element needs a visible area; a background does not create height by itself.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Background image example</title>
<style>
.hero {
min-height: 60vh;
padding: 4rem 2rem;
color: white;
background-image: url("images/hero.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-color: #222;
}
</style>
</head>
<body>
<section class="hero">
<h1>Welcome</h1>
<p>Text appears over the background image.</p>
</section>
</body>
</html>
The url() can point to a relative file, an absolute URL, or another CSS image value such as a gradient. A relative URL is resolved from the stylesheet’s location, not necessarily from the HTML file. For example, if styles/site.css contains url("../images/hero.jpg"), the image is one directory above styles.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →#1 Best Overall
- HTML CSS Design and Build Web Sites
- Comes with secure packaging
- It can be a gift option
Choose how the image fits
cover: fill the box
background-size: cover scales the image while preserving its proportions until the entire positioning area is covered. When the image and element have different proportions, some of the image is cropped. It is usually the right choice for hero banners when filling the region matters more than showing every pixel.
contain: show the whole image
background-size: contain scales the image so the complete image remains visible without stretching. Empty space may remain around it. Because backgrounds repeat by default, pair it with background-repeat: no-repeat when you want one copy only.
Explicit dimensions
You can set a fixed or responsive size, such as background-size: 400px auto or background-size: 100% 100%. The latter can distort the image, so use it only when distortion is acceptable. The default auto preserves the image’s intrinsic sizing behavior.
| Goal | Recommended declarations | Trade-off |
|---|---|---|
| Fill a hero or card | background-size: cover; background-repeat: no-repeat; |
Edges can be cropped. |
| Show an entire diagram or logo | background-size: contain; background-repeat: no-repeat; |
Unused space can remain. |
| Tile a texture | background-size: auto; background-repeat: repeat; |
The image repeats across the element. |
Control the focal point with background-position
background-position: center centers the image in both directions. Use keywords such as top, right, or bottom, percentages such as 50% 20%, lengths such as 20px 0, or edge offsets such as right 2rem bottom 1rem.
.hero {
background-position: 50% 20%; /* keep a face near the top visible */
}
The first value controls the horizontal position and the second controls the vertical position. With cover, changing this point changes which cropped area remains visible; it does not prevent cropping.
Rank #2
Prevent tiling and provide a fallback color
The initial repeat behavior is repeat. Set background-repeat: no-repeat for a single image. Add background-color so the component still has a usable color if the image fails to load or contains transparent areas.
.banner {
background-color: #1f2937;
background-image: url("/assets/banner.webp");
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
Use the background shorthand carefully
The shorthand combines image, position, size, repeat, attachment, clipping, origin, and color. A slash separates position from size:
.hero {
background: url("images/hero.jpg") center / cover no-repeat #222;
}
Values omitted from the shorthand revert to their initial values. If a behavior matters to your design, write it explicitly or verify the shorthand’s complete result.
Free tools Windows power users keep installed
One-click scans. No signup required.
Layer an image with a gradient for readable text
Multiple background layers are listed from front to back. Put a gradient first so it appears over the photo:
Rank #3
.hero {
background-image:
linear-gradient(rgba(0, 0, 0, .55), rgba(0, 0, 0, .25)),
url("images/hero.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-color: #222;
}
Each layer can have its own position and size when you provide comma-separated values. A single fallback color applies behind all layers.
Set a page-wide background
Apply the declarations to body when the image should cover the viewport. The html element can also receive a color or image when you need a page-level fallback.
html {
background-color: #111;
}
body {
min-height: 100vh;
margin: 0;
background: url("images/site-bg.jpg") center / cover no-repeat #111;
}
For a fixed viewport effect, you may use background-attachment: fixed, but test on mobile browsers because scrolling and performance behavior can differ.
Responsive and dynamic examples
Change the focal point on small screens
.hero {
min-height: 420px;
background: url("images/desktop.jpg") center / cover no-repeat #222;
}
@media (max-width: 600px) {
.hero {
min-height: 520px;
background-position: 70% center;
}
}
Use a custom property
.card {
--card-image: url("images/card.jpg");
background: var(--card-image) center / cover no-repeat #333;
}
Set the image from JavaScript
const panel = document.querySelector('.panel');
panel.style.backgroundImage = 'url("images/status.jpg")';
Sanitize or constrain any user-controlled value before inserting it into a style. For static content, CSS is simpler and easier to audit.
Rank #4
- Brand: Wiley
- Set of 2 Volumes
- A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
Background image versus an HTML img
Use a CSS background for decoration behind content, visual texture, or a crop that is part of a component’s presentation. Use <img> when the image is content, needs a text alternative, should be discoverable as an image, or must participate in intrinsic layout sizing. A background will not give an empty element dimensions; add height, padding, min-height, or other layout rules.
Troubleshoot a missing or incorrect background
The image does not appear
- Check that the selector matches the element in the rendered HTML.
- Open the image URL directly and correct spelling, capitalization, and URL encoding.
- Recalculate the path relative to the CSS file. Moving a stylesheet often changes a relative URL.
- Inspect the browser’s network panel for a 404, blocked request, or other loading error.
- Confirm the element has height, width, content, padding, or a layout rule that creates visible area.
- Look for another rule overriding
background-imageor thebackgroundshorthand later in the cascade.
The image is unexpectedly repeated
Add background-repeat: no-repeat. This is especially important with contain, where leftover space otherwise may be tiled.
The subject is cropped
That is expected with cover when proportions differ. Change background-position to move the focal point, reduce the element’s aspect-ratio difference, or use contain if the entire image must remain visible.
Recommended Free Tools
The image looks stretched
Check for two-value sizing such as 100% 100%. Replace it with cover, contain, or a width with auto for the other dimension.
Best Value
Text is hard to read
Add a translucent gradient layer, choose a stronger fallback color, or change the focal position so the text sits over quieter image detail. Check the actual rendered states at desktop and mobile widths.
The color shows but the image does not
The fallback color confirms the element is styled. Focus on the URL, network response, content type, permissions, and any content-security policy that may block the image.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Performance and maintenance considerations
- Choose an image dimension appropriate to the largest display area; oversized files increase transfer and decode work.
- Use modern formats where your browser support requirements allow, and keep a fallback color.
- Do not assume a background is lazy-loaded in the same way as an image element. Test loading behavior for your layout.
- Keep focal-point and repeat rules near the component so later shorthand declarations do not silently undo them.
- Test keyboard focus, contrast, and zoom with the real text over the image. Decorative backgrounds do not replace meaningful content or its text alternative.
Or skip the browser setup
If you need a rendered screenshot of a page rather than CSS running in your own browser, ScreenshotNeo provides a one-request website screenshot API and MCP server.
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. Before capture, it can accept the cookie or consent banner like a visitor and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and whether it was billed. Its MCP server lets Claude, Cursor, and other MCP clients use take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Python and Node.js equivalents
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)
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 data = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', data));
Frequently Asked Questions
Can I use a background image without a separate CSS file?
Yes. Put the same declarations in a <style> block in the document head or use an element’s style attribute, although a stylesheet is easier to maintain.
Why does my background disappear when I add the shorthand?
The background shorthand resets omitted background properties. Declare the required image, position, size, repeat, and color together, or place longhand declarations after the shorthand.
How do I make a background image clickable?
A CSS background is not a link. Put an actual link or button over it, or use an <a> containing an <img> when the image itself is the interactive content.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →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.

