How to Set Background Image Size in CSS
Learn when to use cover, contain, fixed sizes, percentages and positioning to make CSS background images fit without unwanted cropping or stretching.
background-size controls how a CSS background image is scaled inside its background positioning area. Use cover to fill the entire element, contain to keep the complete image visible, or a length/percentage when you need a controlled size. Pair it with background-position and background-repeat: no-repeat to control cropping and prevent tiling.
MDN defines background-size as the property that sets the size of an element’s background image. It is widely available in modern browsers. See the MDN background-size reference for formal syntax and compatibility details.
1. Choose the value for your goal
| Goal | Value | What happens |
|---|---|---|
| Fill the element edge to edge | cover |
Preserves the image ratio and crops the overflowing dimension. |
| Show the complete image | contain |
Preserves the ratio and may leave uncovered space. |
| Scale to a known width | 480px auto or 100% auto |
Sets width and derives height from the intrinsic ratio. |
| Set exact dimensions | 480px 180px |
Sets both dimensions; the image can look distorted if the ratio differs. |
| Use the source’s natural size | auto |
Uses intrinsic dimensions when available. |
2. Make a responsive hero fill its area
.hero {
min-height: 22rem;
background-image: url("hero.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-color: #243044;
}
cover scales the image until both dimensions cover the element. If the element and image have different aspect ratios, some of the image is cropped. center distributes that crop evenly; use top, 70% 40%, or another position when the focal subject is elsewhere.
Keep a focal subject in frame
.product-hero {
min-height: 30rem;
background: url("product.jpg") 70% 35% / cover no-repeat;
}
The first percentage controls the horizontal position and the second controls the vertical position. With cover, positioning works against the difference between the rendered image size and the positioning area, so it changes which cropped region is visible.
3. Keep the entire image visible
.diagram-panel {
min-height: 20rem;
background-color: #f4f6f8;
background-image: url("architecture-diagram.png");
background-size: contain;
background-position: center;
background-repeat: no-repeat;
}
contain scales the image so every pixel fits inside the area without stretching. If the aspect ratios differ, the unused bands show the background color. Always add no-repeat; otherwise a smaller contained image can tile across the remaining space.
4. Set a width, height, or percentage
One value with automatic height
.banner {
background-image: url("banner.jpg");
background-size: 480px auto;
background-position: center top;
background-repeat: no-repeat;
}
A single length or percentage sets the width and leaves the other dimension as auto. The browser preserves the intrinsic ratio when the source provides one.
Scale to the container width
.fluid-banner {
background-image: url("banner.jpg");
background-size: 100% auto;
background-position: center top;
background-repeat: no-repeat;
}
100% auto makes the image as wide as the background positioning area and derives its height. It can leave vertical space in a taller element; it does not force edge-to-edge coverage like cover.
Set both dimensions
.thumbnail {
width: 480px;
height: 180px;
background-image: url("photo.jpg");
background-size: 480px 180px;
background-repeat: no-repeat;
}
Two values explicitly set width and height. Use this only when distortion is acceptable or the source already has the same ratio. For proportional scaling, use auto for one dimension.
5. Understand the sizing area
Percentages are relative to the background positioning area. By default that area is the padding box, and it can change with background-origin.
.card {
padding: 2rem;
background-origin: border-box;
background-size: 100% auto;
background-position: center;
background-repeat: no-repeat;
}
Use background-origin: content-box, padding-box, or border-box when the image must be sized against a specific box. Remember that the element still needs a visible width and height (or content) for a background to appear.
6. Combine declarations with the background shorthand
.hero {
background: #243044 url("hero.jpg") center / cover no-repeat;
}
In the shorthand, put background-size after background-position, separated by a slash. Longhand properties are often easier to debug when several layers or conditional rules are involved. The MDN background reference documents the shorthand grammar.
7. Use multiple background images
.feature {
background-image: url("grain.png"), url("mountains.jpg");
background-size: auto, cover;
background-position: center, center;
background-repeat: repeat, no-repeat;
background-color: #182230;
}
Comma-separated values map by layer: the first image gets the first size, position, and repeat value. The first layer is painted above later layers. Include a value for every layer you want to control.
8. Make the element and image responsive
.hero {
min-height: clamp(18rem, 55vw, 42rem);
background: url("hero.jpg") center / cover no-repeat;
}
@media (max-width: Fortyem) {
.hero {
background-position: 62% center;
}
}
Use a stable aspect ratio or a content-driven minimum height so the crop is predictable. If mobile and desktop need different compositions, switch to a separately cropped source with a media query rather than forcing one image to serve every ratio.
9. Background image versus an img element
Use a background when the image is decorative or belongs to a visual surface behind content. Use an <img> when the image is meaningful content, needs alternative text, should participate in document sizing, or should be discoverable as an image resource. CSS backgrounds do not provide an alt attribute.
10. Troubleshooting
The subject is cut off
Cause: cover must crop when ratios differ. Fix: adjust background-position, change the container ratio, reduce the focal area, or use a source image composed for the target ratio. Switch to contain when every pixel matters.
There are blank bands
Cause: contain preserves the whole image and leaves unused space for a ratio mismatch. Fix: choose cover for edge-to-edge fill, or retain contain and set a deliberate background-color.
The image repeats
Cause: backgrounds repeat by default. Fix: add background-repeat: no-repeat, especially with contain or fixed sizes.
The background is invisible
Cause: the element has no visible area, the URL failed, or positioning places the image outside the area. Fix: give the element a height or content, verify the URL in the browser network panel, add a temporary background color, and check background-position, background-origin, and stacking rules.
The image looks stretched
Cause: both dimensions were forced to values with a different ratio. Fix: use cover, contain, or one dimension plus auto.
The image looks soft
Cause: the source bitmap is being enlarged beyond its natural resolution. Fix: provide a larger source, use responsive image variants where appropriate, or avoid a fixed background size that exceeds the source’s useful resolution.
11. Performance and reliability checklist
- Use appropriately sized, compressed images; a CSS background does not remove download cost.
- Set a fallback
background-colorso the layout remains usable while the image loads or if it fails. - Reserve space with a height,
min-height, or aspect-ratio strategy to avoid layout surprises. - Use
coverfor a decorative hero andcontainfor diagrams, screenshots, and product artwork where cropping loses information. - Test the focal point at narrow, wide, tall, and short viewport ratios.
- For meaningful images, prefer an
<img>with alternative text and responsive loading controls.
12. Inspect the result with a screenshot
When a responsive crop is difficult to review manually, capture representative viewport sizes and compare the output. ScreenshotNeo is a website screenshot API and MCP server. It accepts one GET request and returns PNG, JPEG, WebP, or PDF, with options for device presets, custom viewports, dark mode, retina scale, custom CSS and JavaScript, waiting rules, hidden selectors, and full-page capture.
Or skip the browser setup
Use ScreenshotNeo to render the page at the viewport you need and inspect the actual CSS result. Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are never billed, and the response identifies the verdict and billing status in headers. Its MCP server lets AI agents such as Claude and Cursor take screenshots. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.
See the ScreenshotNeo API documentation for all options.
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}`);
Create a free ScreenshotNeo account and get 1,000 screenshots a month with no card.
FAQ
What is the simplest rule?
Use cover for full-bleed surfaces and contain when the complete image must remain visible.
Does background-size change the element’s height?
No. It scales the painted background; the element still needs its own dimensions from content, height, min-height, or layout.
Can I use percentages?
Yes. Percentages are relative to the background positioning area, which can be changed with background-origin.
How do I stop distortion?
Preserve one dimension with auto, or use cover or contain instead of forcing unrelated width and height values.
When should I use background-position?
Use it whenever cropping matters, especially with cover. Move it toward the image’s focal subject.


