Set background-size: cover on the element that should display the image, then choose its dimensions and focal point. cover scales the image proportionally until both the element’s width and height are covered, so the trade-off is cropping rather than distortion.
The reliable full-page pattern
For a background intended to span the browser viewport, apply the declarations to a page-level element such as html. Add a fallback color, prevent tiling, center the image initially, and use cover:
html {
background-color: #18202a;
background-image: url('/images/site-background.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
body {
margin: 0;
min-height: 100vh;
}
MDN defines cover as scaling an image, while preserving its ratio, to the smallest size that completely covers the container. If the image and viewport have different proportions, some edges are outside the visible area. That is expected; the image is not being stretched.
The background belongs to the element that receives these declarations. The image does not create content height by itself, so a section still needs content, an explicit height, or a minimum height. The MDN background-size reference documents how sizing and uncovered areas work.
#1 Best Overall
Choose the element that should be filled
Whole page or viewport
Use a page-level element when the visual should continue behind the page’s content. The pattern above gives the document at least one viewport of height. Long pages can extend beyond the first viewport; the background behavior you choose should match whether the image is tied to the viewport or to the document.
A hero, banner, or content section
Put the declarations on the section itself and give that section the area you want covered:
.hero {
min-height: 70vh;
padding: 4rem 1.5rem;
color: white;
background-color: #243447;
background-image: url('/images/hero.jpg');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
Here, cover fills the .hero box, not the entire page. If the section’s text makes it taller than 70vh, the box grows and the image is sized against the larger box.
cover, contain, or explicit dimensions?
Choose the sizing mode according to what must remain visible:
| Value | What it prioritizes | Result when proportions differ | Use it when |
|---|---|---|---|
cover |
Edge-to-edge coverage | Part of the image is cropped | You cannot tolerate empty areas behind the element |
contain |
The complete image | Uncovered space can remain | Every part of a logo, diagram, or artwork must be visible |
100% 100% |
Independent width and height | The image can be distorted | Only when distortion is deliberately acceptable |
MDN’s background-size documentation describes both proportional values and explicit dimensions. Do not use 100% 100% as a substitute for cover when the source image’s shape matters.
Rank #2
- HTML CSS Design and Build Web Sites
- Comes with secure packaging
- It can be a gift option
Control which part gets cropped
Start with background-position: center
Centering keeps the middle of the image visible as the container changes shape:
.hero {
background-position: center;
}
That is a good default for scenery or abstract textures, but it may cut off a person or product placed near an edge.
Protect an off-center subject
Move the focal point with keywords or percentages:
.hero {
background-position: 70% center;
}
/* Keep the top of a tall subject visible */
.portrait {
background-position: center top;
}
The first percentage controls the horizontal position and the second controls the vertical position. Test the narrowest and widest layouts that matter to your design. The MDN background-position reference lists the accepted keyword and coordinate forms.
Recommended Free Tools
Keep the image from tiling
background-size controls scale, while repetition is a separate setting. Add background-repeat: no-repeat whenever a single photographic or illustrative background is intended. A fallback background-color remains visible beneath transparent pixels, uncovered regions, or an image that cannot load.
Fixed versus scrolling backgrounds
For a normal background, the positioning area follows the element’s background origin (the padding box by default). With background-attachment: fixed, MDN says the positioning area used for sizing is the entire viewport:
Rank #3
- 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
html {
background: #18202a url('/images/site-background.jpg') center / cover no-repeat fixed;
}
Use fixed attachment only when that viewport relationship is part of the design. Otherwise omit it and let the background belong to its element. The shorthand above is equivalent to setting color, image, position, size, repeat, and attachment separately; writing longhand while debugging can make each setting easier to inspect.
Make the background work with real content
Add a readable overlay without editing the source image
A translucent gradient can sit above the image while text remains in normal document flow:
.hero {
color: #fff;
background-image:
linear-gradient(rgba(0, 0, 0, .42), rgba(0, 0, 0, .42)),
url('/images/hero.jpg');
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
In a multiple-background declaration, the first layer is painted above the next one. Keep the image URL as the final layer so the gradient can darken it.
Do not put essential information only in CSS
CSS backgrounds have no alt attribute. If the image communicates information essential to the page’s purpose, place a semantic image or an equivalent text description in the document instead. MDN makes this accessibility distinction in its background property guidance. A purely decorative texture can remain a CSS background.
Account for text and controls
Check contrast where headings, buttons, and form fields sit over the crop. Keep important content in HTML so it can reflow when the section becomes taller or narrower; do not rely on a particular crop to reserve space for text.
Rank #4
Troubleshoot a background that does not fill
- The image covers only a thin strip. Inspect the element carrying the background. Its height is probably only the height of its content. Add an appropriate
min-heightor height to that element, and remember that the background itself does not create height. - The image repeats. Add
background-repeat: no-repeat. Repetition is independent ofcover. - You see blank bands. Verify that
background-size: coveris applied to the intended element and that no later rule overrides it. If the full image must remain visible, those bands may be the expected result ofcontaininstead. - The subject is cut off. Change
background-positionfromcenterto a keyword such astopor to percentage coordinates that keep the subject inside the crop. - The image is stretched. Remove independently forced dimensions such as
100% 100%and usecoverorcontainto preserve the source ratio. - The fallback color is all you see. Open the image URL directly, check its path and case, and inspect the browser’s network panel for a failed request. Keep the fallback color useful while the image loads or when it is unavailable.
- The page background stops sooner than expected. Confirm whether the image is attached to
html,body, or a nested section. The receiving element determines the scope; a section background cannot fill areas outside that section. - A fixed background behaves unexpectedly. Check whether
background-attachment: fixedis intentional. Fixed attachment uses the viewport as the sizing area, unlike the normal element-based positioning area.
Practical image and loading decisions
Choose an image whose subject can tolerate the crop produced by the container’s likely proportions. A wide landscape may work well in a desktop hero but lose its subject on a tall phone viewport; an image with useful space around its focal point gives background-position more room to adapt.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Keep a solid fallback color that matches the design. It prevents a transparent region or a temporary load failure from exposing an unreadable background. If the image is decorative, avoid making the page depend on it for meaning. If it is meaningful, provide that meaning semantically in the document.
When you change viewport, position, or overlay rules, verify the actual rendered page at representative sizes rather than judging only the source CSS. The browser’s responsive tools let you inspect the crop, while an automated capture can provide repeatable visual checks.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
ScreenshotNeo can capture the rendered page after your CSS is deployed, which is useful for checking whether the background fills the intended element at a chosen viewport. Its API accepts one GET request and returns a PNG, JPEG, WebP, or PDF. Relevant options include full-page capture with lazy images loaded, device presets or a custom viewport, retina scale, dark mode, custom CSS and JavaScript, waiting for a selector or network idle, and hiding selectors that would obscure the result.
Use the ScreenshotNeo API documentation for the full parameter list. A basic request is:
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 minuteWindows 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 reinstallBest Value
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 accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; 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. Its MCP server gives Claude, Cursor, and other MCP clients tools named 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; every feature is available on every plan. Create a free ScreenshotNeo account to check your background rendering without setting up a browser automation stack.
Frequently Asked Questions
Can I combine a CSS background with a normal image element?
Yes. Use the CSS background for decorative coverage and an <img> for content that needs alternative text, intrinsic dimensions, or independent loading behavior. Do not make the same visual information redundant for screen-reader users.
How do multiple background images layer?
List layers separated by commas: the first listed layer is painted on top, and the last listed image is closest to the element. Give each layer its own position, repeat, and size value when their behavior differs.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Will a CSS background always appear when a page is printed?
Not necessarily. Printing is controlled by the browser and the user’s background-graphics setting, so provide readable foreground content and colors that still make sense if the decorative image is omitted.
The Bottom Line
Use background-size: cover on the element whose area you want filled, set a real height or minimum height, and tune background-position for the subject. You will get edge-to-edge coverage with proportional scaling and intentional cropping instead of distortion.
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.




