October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
background-size

How to Set the Background Image Size on a Website with CSS

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

Set the background-size property on the element that owns the background-image. Use cover for an edge-to-edge hero or panel, contain when every part of the image must remain visible, or explicit lengths and percentages when you need a controlled rendered size.

.hero {
  background-image: url("hero.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

cover preserves the image’s proportions but can crop an edge. contain preserves the complete image but can leave empty bands. The correct choice depends on whether coverage or complete visibility matters more.

What background-size controls

According to MDN Web Docs, background-size sets the size of an element’s background image. It does not resize an ordinary inline <img>; it applies to images supplied through background-image.

The property’s initial value is auto auto. You can provide a keyword, one size, or two sizes:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#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
Value Result Use when
cover Scales proportionally until the entire background positioning area is covered; one axis may be cropped. You need a full-bleed hero, banner or section.
contain Scales proportionally so the whole image fits inside the area; uncovered space may remain. Every part of a logo, diagram or product image must show.
300px or 50% Sets one dimension; the other remains auto and keeps the image ratio. You want a particular rendered width or height.
300px 200px Sets width and height independently, which can distort the image. The exact box is more important than natural proportions.
auto Uses the image’s intrinsic dimension for that axis. You are combining a fixed axis with natural sizing.

Values can be combined for multiple background layers by separating each layer’s size with commas, in the same order as the corresponding background-image values.

Choose between cover and contain

Use cover to fill the element

cover scales the image until no part of the element’s background positioning area is uncovered. If the image and element have different aspect ratios, the excess is cropped. A centered, non-repeating hero usually starts with:

.hero {
  min-height: 420px;
  background: #172033 url("hero.jpg") center / cover no-repeat;
}

The color is a fallback while the image loads and remains visible wherever the image does not cover an area or contains transparent pixels. Move the focal point with background-position:

.hero {
  background-size: cover;
  background-position: 65% center;
}

/* Keep the top of a portrait subject visible */
.portrait-hero {
  background-position: center top;
}

Use contain to show the whole image

contain fits the complete image inside the area while preserving its ratio. The remaining space shows the element’s background color. Set background-repeat: no-repeat or the image can tile into that space, as explained in MDN’s background resizing guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.diagram {
  min-height: 360px;
  background-color: #f3f5f7;
  background-image: url("architecture.svg");
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
}

Set an exact or responsive size

One value: preserve the ratio

With one length or percentage, that value sets the background width and the height is calculated automatically. For example:

.card {
  background-image: url("texture.png");
  background-size: 300px;
  background-repeat: no-repeat;
}

.banner {
  background-size: 50%;
  background-repeat: no-repeat;
}

A percentage is relative to the background positioning area, normally the padding box established by background-origin. It is not automatically the viewport width. With background-attachment: fixed, the reference area is the viewport. See MDN’s reference for these percentage rules.

Two values: set width and height

.badge {
  background-image: url("badge.png");
  background-size: 120px 80px;
  background-repeat: no-repeat;
}

Independent dimensions can stretch the source. If distortion is unacceptable, use one value with auto, such as 120px auto, or use contain.

Responsive sizing with clamp()

CSS functions work as length values, so a background can grow between limits:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.hero {
  background-size: clamp(520px, 75vw, 1200px) auto;
  background-position: center;
  background-repeat: no-repeat;
}

This is different from cover: the image has a bounded size and may leave uncovered space. Supply a background color for that space.

Build a complete full-page background

Apply the image to the element that should paint it. For a page-wide background, that is commonly body (or a dedicated wrapper):

html, body {
  min-height: 100%;
}

body {
  margin: 0;
  color: white;
  background-color: #101827;
  background-image: url("site-background.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

A fixed attachment uses the viewport as the reference area for percentage sizing. It can also behave differently on mobile browsers, so test scrolling on the devices your audience uses. If you do not need a viewport-fixed effect, omit background-attachment: fixed.

Combine layers, overlays and positioning

Multiple backgrounds are listed from front to back. Give each image its own size and position:

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.
.hero {
  background-image:
    linear-gradient(rgba(0, 0, 0, .45), rgba(0, 0, 0, .45)),
    url("hero.jpg");
  background-size: cover, cover;
  background-position: center, center;
  background-repeat: no-repeat, no-repeat;
}

The gradient is a separate layer, so it needs a corresponding size and position. A shorthand form is valid when the slash separates position from size:

.hero {
  background: #182235 url("hero.jpg") center / cover no-repeat;
}

Keep important content from being cropped

  1. Identify the subject that must remain visible.
  2. Try background-position, using keywords such as top, right, or percentages such as 70% center.
  3. Give the section a stable minimum height so responsive text does not unexpectedly change the crop.
  4. Use a different, wider or taller source image at a breakpoint if one composition cannot work at every ratio.
  5. Choose contain when cropping is unacceptable, and design the surrounding color or spacing for the resulting empty bands.
.hero {
  min-height: 28rem;
  background: #202a3a url("desktop-hero.jpg") center / cover no-repeat;
}

@media (max-width: 600px) {
  .hero {
    min-height: 34rem;
    background-image: url("mobile-hero.jpg");
    background-position: 60% center;
  }
}

Accessibility and loading considerations

A CSS background is decorative by default and has no alternative text. Do not put essential words, prices or instructions only in the image; place that information in HTML. If the image communicates meaningful content, an <img> with useful alt text is usually a better semantic choice.

Provide a background color that maintains readable contrast before the image is available and behind transparent pixels. A text overlay may need its own solid or translucent layer, as in the gradient example above.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot the common failures

The image does not change size

  • Check that background-size and background-image are on the same element.
  • Confirm the element has dimensions. A block with no content, height or padding may have no visible area.
  • Inspect computed styles for a later rule, inline style or shorthand declaration overriding your value.

contain produces a tiled pattern

Add background-repeat: no-repeat. Tiling is the default behavior when the fitted image does not cover the entire area.

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

cover cuts off the subject

That cropping is expected when aspect ratios differ. Adjust background-position, change the source composition, or switch to contain if complete visibility is required.

A percentage looks unexpectedly large or small

Measure the element’s background positioning area rather than the viewport. Check padding and background-origin; also check whether background-attachment: fixed changes the reference area to the viewport.

Transparent areas show the wrong color

Set background-color explicitly. The color is visible wherever the image is transparent or leaves uncovered space.

The image is stretched

You probably supplied two mismatched dimensions, such as 300px 200px for a source with another ratio. Use auto for one axis, one size value, cover, or contain.

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.

Or skip the browser setup

If you need a rendered screenshot of the finished page rather than CSS preview work, ScreenshotNeo returns a PNG, JPEG, WebP or PDF from one request. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; bot checks, 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 for Claude, Cursor and other MCP clients.

Use the API documentation at screenshotneo.com/docs/ for all options, including viewport and device presets, full-page lazy-image loading, CSS selectors, dark mode, retina scale, custom CSS or JavaScript, waits, request blocking, cookies, headers, geolocation, PDFs, caching, signed links, asynchronous webhooks and bulk capture.

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}`);

The Free plan includes 1,000 screenshots a 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.

Quick decision guide

  • Choose cover for edge-to-edge visual impact.
  • Choose contain plus no-repeat when the complete image matters.
  • Choose one length or percentage for proportional custom sizing.
  • Choose two values only when you accept possible distortion.
  • Use background-position, responsive source images and a fallback color to control the result.

Frequently Asked Questions

Can I use background-size with several background images?

Yes. Separate each layer’s size with commas and keep the order aligned with the comma-separated background-image layers.

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

Is cover the same as stretching an image?

No. cover preserves the image ratio and crops the excess; it does not independently stretch width and height.

Why is an img element unaffected by my rule?

background-size applies only to CSS background images. Resize an img with its own width, height and object-fit rules.

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.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver 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.