Resize background image in div using CSS
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
.
To your div, apply the following:
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:
Object-fit for img tags
When using img tags rather than background images, consider using object-fit
which allows for similar resizing behavior:
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:
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:
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:
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
orsource
for different background images on diverse breakpoints. - Image sets:
srcset
andsizes
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.
Was this article helpful?