Explain Codes LogoExplain Codes Logo

Resize background image in div using CSS

html
responsive-design
css
best-practices
Nikita BarsukovbyNikita Barsukov·Sep 28, 2024
TLDR

To resize a background image in a div with CSS, use background-size with the cover option to fill the div fully, or contain to fit the entire image within the div. Prevent image repetition by setting background-repeat to no-repeat and center the image with background-position: center.

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

To your div, apply the following:

<div class="div-bg"></div>

This will ensure an adequately sized and positioned image.

Stretch-image-to-fill approach

Should you need to stretch the image to precisely fit the div, regardless of the image aspect ratio, you can use 100% 100%. It is less common due to potential image distortion. Here's a quick example:

.stretched-bg { background-size: 100% 100%; /* Image may appear stretched like bubble-gum */ }

Object-fit for img tags

When using img tags rather than background images, consider using object-fit which allows for similar resizing behavior:

.img-fit { object-fit: cover; /* Or contain, just like background-size */ }

Bear in mind that object-fit has no support in IE.

Media queries for responsive design

Use media queries to adjust your images depending on the screen size. This makes for stylishly fitting background images on all devices:

@media (max-width: 768px) { .div-bg { background-size: contain; /* Let's not scare mobile users with giant images */ } }

Potential visual impacts

Each background-size option will impact your visuals differently:

  • Contain: Ensures the entire image is visible but may leave unfilled space.
  • Cover: Fills the div potentially cropping part of the image.
  • 100% 100%: Forces the image to fit precisely, which may cause distortions.

Cross-browser support with jQuery

If you're all for diverse browser support, jQuery is your comrade for augmenting compatibility:

$(window).resize(function() { $('.div-bg').css('background-size', window.innerWidth > window.innerHeight ? 'cover' : 'contain'); /* We've got eyes on all devices! */ });

Best practice involves leaning on vanilla CSS where possible, but JavaScript-based fallbacks might lend a helpful hand.

Real-time practical examples

Codepen demo is our live ground for testing various background-size implementations:

View Codepen demo

Tinkering gives lasting lessons. You'll see and feel the difference in real-time.

Get ready for different scenarios

There are a plethora of complex scenarios:

  • Art direction: Use media attributes with picture or source for different background images on diverse breakpoints.
  • Image sets: srcset and sizes offer different scaled images depending on screen resolution and density.
  • Vector images: Logos or icons scream for SVG formats which assure perfect scalability and minimal file size.