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 show the whole image (which can leave empty space). Add background-position, background-repeat: no-repeat, and a fallback background-color for a reliable result.
The basic CSS pattern
This example creates a hero section with a 24rem minimum height, a fallback color, centered positioning, no tiling, and proportional scaling:
.hero {
min-height: 24rem;
background-color: #243044;
background-image: url("/images/hero.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
background-image attaches one or more images to an element; it does not set the element’s width or height. If the element has no content, padding, or explicit dimensions, there may be no visible box in which to paint the image. The URL can be absolute, root-relative (such as /images/hero.jpg), or relative to the CSS file (such as ../images/hero.jpg).
Choose the element and give it a visible area
A section or component
For a banner, card, or callout, put the background on that component and control its size with content, padding, min-height, or a fixed height:
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →.announcement {
min-height: 12rem;
padding: 3rem 2rem;
background: url("/images/announcement.webp") center / cover no-repeat;
}
The entire page
Applying the image to body covers the body element’s box, not an abstract infinite canvas. Ensure the document can grow naturally and decide whether the image should scroll with content:
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
html {
min-height: 100%;
}
body {
min-height: 100vh;
margin: 0;
background-color: #101722;
background-image: url("/images/site-background.jpg");
background-position: center top;
background-repeat: no-repeat;
background-size: cover;
}
Use a component-specific element when only one area needs the image. A page-wide background can make text contrast and mobile cropping harder to manage.
cover versus contain
| Value | What it does | Use it when | Trade-off |
|---|---|---|---|
cover |
Scales proportionally until the box is completely filled. | The container must have no empty background space. | Parts of the image can be cropped. |
contain |
Scales proportionally until the entire image fits inside the box. | Every part of the image must remain visible. | Unfilled space can remain; disable repetition if you do not want tiling. |
auto (initial behavior) |
Uses the image’s intrinsic dimensions unless other sizing rules apply. | You intentionally want the image’s natural scale. | It may not fill the component or may repeat. |
Do not force different width and height values that distort the source. Select cover or contain according to whether filling or preserving the complete image matters more.
Control cropping and repetition
Position the focal point
With cover, the browser must crop whichever edges exceed the box. background-position: center centers that crop. Use top, right center, or percentages when the subject is off-center:
.hero {
background-size: cover;
background-position: 70% 35%;
}
The first percentage is horizontal and the second is vertical. For a portrait subject near the left edge, values such as 25% center can keep the subject in view. Check the result at the narrowest viewport you support.
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
Stop the image from tiling
.panel {
background-image: url("/images/panel.jpg");
background-repeat: no-repeat;
}
Repetition is useful for small textures, but it is usually undesirable for photographs. If you use contain, explicitly set no-repeat so the remaining space stays a single fallback color.
Use the background shorthand safely
The shorthand combines color, image, position, size, and repetition:
.hero {
background: #243044 url("/images/hero.jpg") center / cover no-repeat;
}
The slash separates position from size. A shorthand can reset omitted background subproperties to their initial values. Therefore, place it before any longhand overrides, or include every value you depend on. In a comma-separated list, the first background layer is painted closest to the user:
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 →.hero {
background:
linear-gradient(rgb(0 0 0 / 45%), rgb(0 0 0 / 45%)),
url("/images/hero.jpg") center / cover no-repeat;
background-color: #243044;
}
The gradient darkens the image for text while the color remains a fallback if the image fails to load.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
Make overlaid text readable
Text must remain legible over the lightest and darkest portions of the actual image. MDN guidance uses a minimum contrast ratio of 4.5:1 for normal body text and 3:1 for larger text (at least 24px, or bold text at least 18.66px). A translucent overlay, solid text panel, or different focal crop can help:
.hero {
display: grid;
align-items: end;
min-height: 24rem;
padding: 2rem;
color: white;
background-image:
linear-gradient(rgb(0 0 0 / 55%), rgb(0 0 0 / 25%)),
url("/images/hero.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
Evaluate contrast where the text sits, not only against an average color. A CSS background is decorative from an accessibility perspective: assistive technology does not receive special information about it. If the picture communicates information necessary to understand the page, use a semantic HTML image instead.
Background image or HTML image?
| Question | CSS background | HTML img/picture |
|---|---|---|
| Is the image decorative? | Appropriate for visual decoration. | Also possible, but unnecessary semantics. |
| Does it convey meaning? | Not exposed as image content to assistive technology. | Provide meaningful alt text or an empty alt for purely decorative images. |
| Must the complete image be visible? | Use contain, accepting possible empty space. |
Intrinsic sizing and object-fit can provide content-oriented behavior. |
| Do you need responsive sources? | Use media queries or image-set() for decorative art. |
Use picture and srcset for content images and alternatives. |
For a meaningful chart, product photo, map, or instructional diagram, place the image in the document and write an appropriate text alternative. Do not hide essential information in a background.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesResponsive backgrounds and high-density screens
Choose a different crop or asset
.hero {
min-height: 20rem;
background-image: url("/images/hero-wide.jpg");
background-position: center;
background-size: cover;
}
@media (max-width: fortyrem) {
.hero {
min-height: 28rem;
background-image: url("/images/hero-tall.jpg");
background-position: 60% center;
}
}
Replace fortyrem with a valid numeric breakpoint such as 40rem; the example is shown to emphasize that the breakpoint is your design decision. A portrait-oriented asset often preserves a subject better on a narrow screen than repeatedly shifting a wide image.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Offer density-specific decorative images
.logo-wall {
background-image: image-set(
url("/images/wall-1x.jpg") 1x,
url("/images/wall-2x.jpg") 2x
);
background-size: cover;
background-repeat: no-repeat;
}
For content images, prefer HTML picture and srcset, which let the browser select an appropriate source while retaining semantics and text alternatives.
Fallbacks, loading, and performance
- Always specify a matching
background-color; it remains visible when an image request fails or while the image is loading. - Use appropriately compressed JPEG, WebP, or PNG files. Avoid shipping a camera-original file when a smaller asset provides the same visual result.
- Keep the focal subject away from edges that
covermay crop, and test with long translations or zoomed text. - Do not use a large decorative background where a small texture or solid color would work.
- Cache stable image URLs at your web server or CDN, and avoid changing query strings unnecessarily.
These choices reduce transfer cost and improve perceived loading without changing the CSS behavior.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Common problems and fixes
The image does not appear
- Open the image URL directly and correct spelling, capitalization, and relative-path location.
- Inspect the element to confirm the selector matches and another rule is not overriding it.
- Check that the element has content, padding, an explicit height, or a
min-height. - Look for a later
backgroundshorthand that reset your image.
The image tiles
Add background-repeat: no-repeat. If you intended a texture, choose explicit repeat behavior such as repeat-x or repeat-y.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchThe image is cropped
Cropping is expected with cover. Change background-position, select a better source crop, or switch to contain when the complete image is more important than filling the box.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
There is empty space or the image looks distorted
Use contain when showing the whole image is the priority, and keep no-repeat if the remaining area should show only the fallback color. Do not set independent dimensions that change the aspect ratio.
Text is difficult to read
Add a gradient or solid backing, reposition the focal point, or move the text. Verify the contrast ratio against the rendered image area rather than relying on the source image’s average color.
The image contains important information
Move it into semantic HTML and provide alternative text. A CSS background is not announced as image content by screen readers.
Free tools Windows power users keep installed
One-click scans. No signup required.
Or skip the browser setup
If you need a screenshot of the finished page rather than a local visual check, ScreenshotNeo returns a PNG, JPEG, WebP, or PDF from one GET request. It accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its 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 all 63 options, including full-page and selector captures, device presets, retina scale, custom CSS and JavaScript, waits, blocked resources, cookies, headers, geolocation, PDFs, caching, signed links, asynchronous webhooks, bulk capture, usage data, and the OpenAPI specification. The free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account.
Quick checklist
- Attach
background-imageto the intended element. - Give that element a visible size.
- Choose
coverfor a filled box orcontainfor the complete image. - Set
background-positionfor the subject’s focal point. - Use
background-repeat: no-repeatunless tiling is intentional. - Provide a fallback
background-color. - Check text contrast and use HTML image markup when the image conveys information.
- Test narrow viewports, zoom, loading failure, and high-density screens.
References
- MDN: background-image
- MDN: background-size
- MDN: background shorthand
- web.dev: Backgrounds
- web.dev: Responsive images
- web.dev: Images
Frequently Asked Questions
Can I use a CSS variable for the background URL?
Yes. Define a custom property such as --hero-url: url("/images/hero.jpg") and use background-image: var(--hero-url); keep a background color and validate the computed rule in developer tools.
Why does changing the image file not update immediately?
A browser or CDN may be serving a cached URL. Rename the asset or use a deliberate versioned URL after confirming your cache policy.
Should I preload a background image?
Only when it is critical to the initial viewport and you have measured a benefit. Otherwise, a correctly sized asset and normal caching are simpler.
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.

