Key takeaways
- background-size: cover fills the box while preserving aspect ratio and cropping overflow.
- background-size: contain preserves the full image and may leave unused space.
- background-size: 100% 100% forces an exact fit and distorts mismatched aspect ratios.
“Stretch” can mean fill the box, preserve the whole image, crop the edges, repeat a texture, or deliberately distort the pixels. Those outcomes use different CSS and should not be treated as interchangeable.
What matters most
- Explicit length or percentage values provide controlled scaling for art-directed layouts.
- background-repeat can fill an area efficiently when the source is designed as a tile.
- The image-set function can select denser assets for displays that can use them.
Define the intended sizing behavior
Stretch is ambiguous. It may mean filling a box while cropping edges, preserving the complete image with empty space, forcing the image into an exact shape, repeating a tile, or scaling to explicit dimensions. Name the intended result before selecting a CSS property because each option has different visual and performance consequences.
A background image is decorative paint and contributes no intrinsic width or height to its element. The container needs content, dimensions, a minimum height, an aspect ratio, or another layout rule before the background becomes visible. If the image conveys essential meaning, use an img or picture element with appropriate alternative text instead.
Fill
Use cover when the box must be completely painted and edge cropping is acceptable.
Fit
Use contain when every source pixel must remain visible.
Distort
Use independent width and height scaling only when altered proportions are intentional.
Fill the box with cover
background-size: cover preserves the source aspect ratio and scales the image until both container dimensions are filled. If source and container ratios differ, the longer image dimension extends beyond the box and is cropped. The browser does not understand which subject matters, so center positioning can still remove a face, product, or label.
Use background-position to protect an approved focal area, then test extreme container shapes. Percentage positioning is based on the difference between the container and rendered image sizes, which is why 100% aligns the far edges rather than shifting the image by one full container width. A separate compact crop is safer when one focal position cannot satisfy every viewport.
Good uses
Photographic heroes, cards, and decorative panels where a full-bleed surface matters more than showing every edge.
Failure signal
If numerous breakpoint-specific position tweaks are required, the composition probably needs another derivative.
Preserve the complete image with contain
background-size: contain preserves aspect ratio and scales until the whole image fits inside the container. Because one dimension can remain uncovered, combine it with a deliberate background color or a compatible repeating treatment. This method suits logos, diagrams, or decorative frames whose full boundary must remain visible.
Contain does not guarantee readability when the source contains text. At narrow sizes, the full artwork may become too small even though nothing is cropped. Important copy should be HTML, and meaningful diagrams usually belong in semantic image markup where alternative text and responsive source controls are available.
Choose the surrounding color
The uncovered region is part of the design, not an accidental blank area.
Check minimum useful size
Preserving the full image is not helpful if its meaningful details become illegible.
Use exact or explicit sizing carefully
background-size: 100% 100% scales the two axes independently to match the container. It guarantees complete coverage without cropping, but it distorts the source whenever aspect ratios differ. Circles become ovals, faces change shape, and logos lose their intended geometry. Reserve this method for abstract textures or intentionally flexible artwork.
One-value and two-value sizes can use lengths, percentages, auto, or viewport-related units. They are useful for art-directed effects such as a fixed-width motif aligned to one side. Remember that viewport units follow the viewport rather than the component, so a reusable card can receive an oversized background when embedded in an unexpected layout.
Preserve one axis
A value such as 100% auto scales width while allowing height to follow the source ratio.
Prefer component-relative rules
Use container dimensions or breakpoints when the artwork belongs to a reusable component.
Repeat tiles and layer backgrounds
A small seamless texture can fill a large area with background-repeat instead of downloading a large bitmap. Control repetition on each axis and verify seams at common zoom levels and pixel densities. Do not repeat photographic subjects or artwork with obvious edges unless the repetition is part of the design.
CSS supports multiple background layers, painted with the first listed layer on top. A gradient can sit above a photograph to improve text separation, while a color provides the final fallback. Keep size, position, and repeat values aligned by layer because mismatched comma-separated lists are difficult to debug.
Tile economy
A purpose-built tile can reduce transfer size, but excessive detail may still make the repeated surface distracting.
Layer restraint
Every additional image can add a request, decode cost, and maintenance responsibility.
Select responsive and high-density assets
Use media queries when the container requires a materially different crop or source size. CSS image-set can provide density or format candidates for one composition, but it does not offer the same width-based selection and semantic behavior as picture and srcset. Include a normal background-image fallback when required by the supported browser matrix.
A high-density candidate should contain enough pixels for the rendered CSS size and display density, but more is not automatically better. Oversized files increase transfer, decode memory, and paint work. Inspect which candidate the browser requests on real devices and ensure it is cached with the expected headers.
Avoid duplicate downloads
Test that preload rules, base declarations, media queries, and image-set do not cause unused candidates to be fetched.
Measure rendered demand
Base derivative dimensions on actual component sizes rather than device marketing resolutions.
Prepare source images for their slots
A single master rarely matches a wide hero, square card, and tall mobile panel equally well. Generate derivatives around the actual container ratios and expected pixel dimensions. Transloadit's /image/resize Robot can create fit or fillcrop outputs, while gravity can guide a crop. The application still decides whether each crop preserves meaning.
Store the original separately, publish only validated derivatives, and use stable versioned references in CSS. Processing fewer purposeful variants usually costs less than producing every size and format combination. Monitor output dimensions and bytes so an incorrect upload or processing change does not silently increase delivery cost.
Review crops
Automatic focal selection is useful for candidates, but branding, safety, and subject preservation require human judgment.
Normalize inputs
Correct orientation and reject unreasonable source dimensions before deriving production backgrounds.
Test accessibility, failures, and operations
Keep essential text and controls out of the background. Verify readable contrast over every final crop, visible keyboard focus, text zoom, reduced-motion behavior, and a usable solid-color state when the image is unavailable. Fixed background attachment can perform poorly or behave differently on mobile, so treat it as an enhancement and test target devices.
Throttle the network and inspect layout stability, Largest Contentful Paint, requested bytes, cache status, and image errors. Test transparent assets, missing files, unusually tall sources, and containers at both ratio extremes. Secure upload and processing endpoints with trusted validation, signed requests where appropriate, and credentials that never enter public CSS or browser code.
Operational checks
Alert on missing derivatives, processing failures, unexpected file sizes, and sustained delivery increases.
Safe rollout
Publish versioned assets, verify production rendering, then switch references while retaining a known-good rollback.
Technical details worth knowing
- With cover, the browser scales until both dimensions fill the box; with contain, it scales until both dimensions fit. The source aspect ratio is preserved in both cases.
- Percentage background positions are calculated from the difference between the container and rendered image sizes, which is why 100% aligns the far edges instead of moving by the full container width.
- Background images do not contribute intrinsic dimensions to an element. The layout needs explicit content, dimensions, aspect-ratio, or padding before the background can occupy visible space.
- Using 100% 100% independently scales both axes and therefore distorts circles, faces, logos, and text whenever source and destination aspect ratios differ.
- Multiple CSS backgrounds are painted in list order with the first layer on top, allowing gradients to protect text without editing the original artwork.
- High-density image candidates only help when their additional source pixels match the rendered size; oversized files still cost bandwidth and decode memory.
A practical approach
- 1
Name the desired visual behavior before choosing a background-size rule.
- 2
Export derivatives around actual container ratios and expected rendered dimensions.
- 3
Set a background color so loading and transparent regions fail gracefully.
- 4
Inspect crops at content extremes and measure transfer size on mobile.
When Transloadit is useful
Use /image/resize to generate derivatives that match the layouts where a background will appear. Supplying a close aspect ratio often produces a better result than asking CSS to stretch one source across every shape.
Architecture boundary
Transloadit does not control CSS rendering. It can create purposeful aspect-ratio variants, while the application chooses whether an image should crop, repeat, distort, or remain fully visible.
Frequently asked questions
What is the difference between cover and contain?
Cover fills the container and may crop edges. Contain displays the whole image and may leave uncovered space. Both preserve the source aspect ratio.
How can I stretch a background without distortion?
Use cover when cropping is acceptable or contain when empty space is acceptable. Independent values such as 100% 100% distort any source whose aspect ratio differs from the container.
Why is my background image not visible?
The element may have no content or dimensions, the URL may have failed, another layer may cover it, or the declaration may be overridden. Inspect the element's computed size and background properties, then check the network request.
Should meaningful images use CSS backgrounds?
Usually not. Use img or picture when the image communicates information because those elements support alternative text, intrinsic dimensions, and responsive source selection.
Can Transloadit choose the CSS sizing mode?
No. Transloadit can generate derivatives that better match intended aspect ratios and sizes. The application must choose whether CSS should crop, contain, repeat, distort, or reposition each image.