Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
accessibility

How to Set a JPG as a Website Background Image with CSS

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set a JPG as a decorative website background with CSS: background-image: url('...'). Give the target element a real width and height, then choose background-size: cover or contain according to whether filling the box or showing the entire image matters more.

.hero {
  background-image: url('/images/photo.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  min-height: 24rem;
  background-color: #263238;
}

Replace the path with the location of your JPG. The image decorates the element; it does not create layout height by itself.

Apply the background to the element that should display it

Use a class on the section, banner, card, or page region that owns the visual:

.hero {
  background-image: url('/images/photo.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  min-height: 24rem;
  background-color: #263238;
  color: white;
}

The URL can be an absolute address or a path relative to the CSS file. If the stylesheet is /css/site.css and the file is /images/photo.jpg, use ../images/photo.jpg from that stylesheet. If the stylesheet is inline in the page, a root-relative path such as /images/photo.jpg is usually easiest.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Attach the class to markup that has content or an explicit size:

#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option
<section class='hero'>
  <h1>Product launch</h1>
  <p>A short message over the photo.</p>
</section>

Padding, text, a fixed height, or a minimum height gives the section a visible box. An empty element with no height can have a perfectly valid background declaration but nothing visible to paint.

Make a JPG fill a section without distortion

background-size controls how the image is fitted while preserving its aspect ratio.

Value What it does Use it when Trade-off
cover Scales the JPG until every part of the element is covered. The section must be completely filled, such as a hero banner. Edges can be cropped, especially when the element and image have different proportions.
contain Scales the entire JPG so no part is cut off. Showing the whole image is more important than filling every pixel. Unused space may remain around the image; set a background color to make that space intentional.

With cover, choose a focal point deliberately. background-position: center top keeps the top of a portrait-oriented subject visible, while background-position: 70% center moves the crop toward the right. You can use lengths or percentages, for example background-position: 20px 40%.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a shorthand declaration when the values are stable

.card {
  background: #263238 url('/images/card.jpg') center / cover no-repeat;
}

The separate properties are easier to override at breakpoints, so keep them separate when mobile and desktop need different images or positions.

Set a JPG as the full-page background

Apply the same properties to body when the image belongs behind the whole document:

body {
  background-image: url('/images/site-background.jpg');
  background-size: cover;
  background-position: center top;
  background-repeat: no-repeat;
  background-color: #263238;
}

cover fits the background to the viewport area being painted, but a long page can reveal the background as the document grows. If the visual should remain fixed while content scrolls, add background-attachment: fixed and test on mobile browsers; fixed backgrounds can be expensive or behave differently on some mobile devices. For a background that should scroll normally, leave the property at its default.

Do not force height: 100% on body unless you also understand how the root element is sized. A minimum height on the region that needs the image is usually safer:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
html, body {
  margin: 0;
}

body {
  min-height: 100vh;
  background: #263238 url('/images/site-background.jpg') center top / cover no-repeat;
}

Control tiling, fallback color, and overlays

Stop accidental repetition

Small images repeat by default. Set background-repeat: no-repeat for a single photographic backdrop. If you intentionally want a texture, use repeat, repeat-x, or repeat-y instead of relying on the default.

Keep a fallback color

A network error, wrong path, blocked request, or slow load can leave the image unavailable. The background-color remains visible and prevents text from sitting on an unpredictable canvas. Pick a color that also supports the foreground content.

Add a readable overlay

Text over a photo can become unreadable where the crop changes. A pseudo-element keeps the image separate from the content:

.hero {
  position: relative;
  isolation: isolate;
  background: url('/images/photo.jpg') center / cover no-repeat #263238;
  color: white;
}

.hero::before {
  content: '';
  position: absolute;
  inset: 0;
  background: rgb(0 0 0 / 0.35);
  z-index: -1;
}

.hero > * {
  position: relative;
}

Check contrast over the actual image at each responsive crop. The commonly used WCAG targets are 4.5:1 for normal body text and 3:1 for large text. A darker overlay or an opaque panel behind the words can make the result robust.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose responsive images instead of sending one oversized JPG everywhere

A single large background file sends the same bytes to a small phone and a wide desktop display. If the compositions or required dimensions differ substantially, switch assets with a media query:

.hero {
  background-image: url('/images/hero-small.jpg');
  background-size: cover;
  background-position: center;
}

@media (min-width: 50rem) {
  .hero {
    background-image: url('/images/hero-large.jpg');
  }
}

Choose files no larger than the display needs, compress the JPG, and avoid placing a high-resolution original in every breakpoint. CSS image-set() can select density-specific candidates, but check current browser support and syntax before depending on it in production.

Use a meaningful HTML image instead when the visual communicates information rather than decoration. HTML can provide an alternative text, while assistive technology receives no special information about a CSS background.

Background image versus an HTML image

Question CSS background HTML <img> or <picture>
Is the image decorative? Yes; suitable for texture, atmosphere, or a purely visual hero. Possible, but adds an element that may not be needed.
Does it convey information? Not suitable as the only representation because screen readers do not announce it. Preferred; provide an appropriate text alternative.
Do you need responsive candidate selection? Use media queries or carefully tested image-set(). Use srcset or picture with browser-selected sources.
Should the image determine layout size? No; the element needs its own content, padding, height, or minimum height. The intrinsic image dimensions can participate in layout, subject to your CSS.

Debug a JPG that does not appear or looks wrong

Work through these checks in order so a visual symptom does not hide a path or layout error.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Verify that the URL points to the real file. Check spelling, directory names, the .jpg extension, and filename case; servers commonly treat Photo.jpg and photo.jpg as different files.
  2. Open the image URL directly in a browser. A 404, redirect to an HTML error page, authentication prompt, or mixed-content block confirms a delivery problem rather than a CSS sizing problem.
  3. Inspect the target element in developer tools. Confirm the stylesheet is loaded, the rule is not crossed out by a more specific selector, and the computed background-image is the URL you expect.
  4. Check the element’s box model. Look for zero height, collapsed children, display: none, clipping, or a parent with no visible area. Add temporary outline: 2px solid red and min-height: 10rem to prove that the box exists.
  5. Use the network panel to find the JPG request. Inspect its status, response type, and request URL. A failed request usually identifies the exact path or server configuration error.
  6. If the image tiles, set background-repeat: no-repeat. If it is stretched, replace a manual width/height rule with cover or contain.
  7. If the subject is missing, change background-position. Test center top, a percentage such as 70% center, or separate positions at mobile and desktop breakpoints.
  8. Retain a background-color and test with the JPG request blocked. This confirms that text, spacing, and contrast remain usable during a failed load.

The CSS rule is present but the image is blank

The most common causes are a zero-height element, a URL resolved relative to the wrong stylesheet directory, or a later rule overriding background-image. The computed-style and network checks above distinguish those cases quickly.

The image repeats or leaves unexpected bands

Repetition means the default tiling behavior is active; add background-repeat: no-repeat. Bands with contain are expected because the full image is being preserved. Use a matching fallback color or switch to cover if filling the box is the priority.

The focal subject is cropped on phones

cover must crop somewhere when aspect ratios differ. Supply a mobile-specific crop, change the mobile background-position, or use contain if cropping is unacceptable.

The background works locally but not after deployment

Check case-sensitive filenames, the deployed directory structure, the final CSS URL, and whether the production page is HTTPS while the image URL is HTTP. Purge or invalidate an old CSS cache after correcting the path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance and reliability considerations

  • Compress the JPG and select dimensions appropriate to the largest box that will display it. A background still downloads even when it is only decorative.
  • Prefer a smaller mobile asset when the desktop composition is much wider or heavier. Media queries also let you choose a crop designed for narrow screens rather than merely shrinking a desktop scene.
  • Keep critical text and layout independent of the image. The fallback color, spacing, and contrast should remain acceptable while the request is pending or fails.
  • Use CSS backgrounds for decoration, not for logos, instructions, charts, or other information that needs an accessible text alternative.
  • Test at narrow and wide widths, high-density displays, slow connections, keyboard navigation, and with images blocked. The crop that looks correct in one viewport may hide the subject in another.

Or skip the browser setup

If you need a dependable screenshot of the finished page rather than a manual browser capture, ScreenshotNeo returns a PNG, JPEG, WebP, or PDF from one GET request. It accepts cookie and consent banners before capture, removes more than 60 known consent platforms plus newsletter popups and chat widgets, and lets you turn each cleanup step off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers.

Use the API documentation at https://screenshotneo.com/docs/ for the full option set, including full-page lazy-image loading, CSS-selector element capture, dark mode, device presets, custom viewport and retina scale, PDF page settings, custom CSS and JavaScript, click and wait actions, request blocking, headers, cookies, user-agent, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage data, and an OpenAPI specification.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

Python

import requests

r = requests.get(
    'https://api.screenshotneo.com/v1/shot',
    params={'access_key': 'YOUR_API_KEY', 'url': 'https://example.com'},
    timeout=90,
)
r.raise_for_status()
open('shot.webp', 'wb').write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.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 shots per month with no card. Paid plans start at $5 for 3,000 shots; Growth is $15 for 15,000, Pro is $39 for 60,000, Scale is $99 for 250,000, and Business is $249 for 1,000,000. Yearly billing gives two months free, and every feature is included on every plan. An MCP server also lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf directly.

Create a free ScreenshotNeo account to get 1,000 screenshots a month without adding a card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

How is a relative background URL resolved?

For an external stylesheet, the path is resolved from that stylesheet’s directory, not from the HTML file. Inline CSS resolves relative to the page URL; use a root-relative path such as /images/photo.jpg when you want a stable site-root location.

Why does changing the JPG file sometimes appear to do nothing?

The browser or a cache layer may still serve the previous URL. Rename the asset, change its URL, or clear the relevant cache, then confirm in the network panel that the response contains the new file.

Can I use a background image on an element with no text?

Yes, but the element still needs a nonzero box from a declared height, minimum height, padding, or another layout rule. A background image never supplies that height by itself.

Quick Recap

SaleBestseller No. 1
HTML and CSS: Design and Build Websites
HTML and CSS: Design and Build Websites
HTML CSS Design and Build Web Sites; Comes with secure packaging; It can be a gift option
$14.18
SaleBestseller No. 2
SaleBestseller No. 4

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.