Explain Codes LogoExplain Codes Logo

Stretch and scale CSS background

html
responsive-design
css
background-size
Alex KataevbyAlex Kataev·Sep 15, 2024
TLDR

Scaling a background image to fill an element can be done by setting background-size to cover, positioning the image in the center of the element, and setting background-repeat to no-repeat.

.element { background: url('image.jpg') center/cover no-repeat; }

This CSS snippet ensures your image will flawlessly cover the entire .element without distorting the image.

Applying minimum dimensions: Aspect ratio preservation

Using min-width and min-height set to 100% can ensure full coverage. However, remember that this might result in cropped edges of the image, as the aspect ratio is not always maintained.

Cross-browser compatibility: Supporting most users

Although background-size: cover; is well-supported, don't forget to account for legacies (or as we fondly call them, pesky legacy browsers). Use vendor prefixes and get that cross-browser compatibility on point.

.element { -webkit-background-size: cover; /* For the Chrome and Safari superfans */ -moz-background-size: cover; /* For the Firefox die-hards */ -o-background-size: cover; /* For that one person still on Opera 12 */ background-size: cover; /* For the progressive crowd (and IE9+) */ }

To summon support for legacy versions of IE, conjure this incantation:

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='yourImage.jpg', sizingMethod='scale')";

Modern toolkits: The cavalry to your rescue

Modernizr and jQuery can help where plain CSS cannot. Modernizr checks if background-size is supported, and helps you set JS-based fallbacks. Consider jQuery's imgsizer plugin when you need responsive and fluid backgrounds and CSS just isn't cutting it.

Maintaining proportions: Aspect ratio

For maintaining an image's aspect ratio while scaling, use "auto" values for width and height, but pair with care if using min-width and min-height set to 100% — it can lead to your image being overscaled and cropped, like your holiday photos taken by your ever-so-enthusiastic aunt.

Full-width vs Full container coverage: Battle of the backgrounds

To fill width of the container and maintaining proportionality, use background-size: 100% auto;. But when achieving full coverage of the container is your endgame, set background-size: 100% 100%.

Media Queries: Serving Responsive Realness

To make your backgrounds behave responsibly... I mean responsively, enlist the help of media queries to adjust background-size according to different resolutions.

Fluid Design: Handling percent in width

If percent based designs are your thing, consider amending scripts to handle percentage widths in a more polished way to avoid awkward stretches or scaling issues.