Read more

CSS: How to force background images to scale to the container, ignoring aspect ratio

Arne Hartherz
July 26, 2021Software engineer at makandra GmbH

You can scale background images in CSS to the container size using background-size ( Demo Show archive.org snapshot ).

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Commonly, we use contain or cover because we want to preserve the image's aspect ratio.
If you do not want to do that, simply provide scaling values for X and Y:

background-size: 100% 100%

(a simple 100% would mean 100% auto and respect the image's aspect ratio)

SVGs with a viewBox will force their aspect ratio

The above may not work for you when using SVG images. In that case, you must remove the viewBox attribute from your SVG.

There is no way to do that in CSS, you must edit the file manually (SVGs are just XML) or use some kind of pre-processing.

You could probably also hack together a solution in JavaScript which downloads the background image file, rewrites the XML string and generates a data: URI. I have not tried that, as it was not relevant for me (and there might be several edge cases).

Posted by Arne Hartherz to makandra dev (2021-07-26 12:44)