Search code examples
cssbackground-imagescalebackground-size

How do I have a background-image only scale down to fit its element, but not scale up?


The div in which I have a background image is of unknown size. It can be 16px high, it can be 1600px, and anything in between. There's a background-image in there that's roughly 440px wide and 250px high.

When the div is higher than 250px, the background image doesn't scale. That's desired behaviour. So far so good.

If the div gets under 250px in height, the background-image is clipped. That's unwanted: I want it to scale to the div's smaller height.

How do I use css (or, if not possible, js) to have a background-image scale down when it doesn't fit its div, but never scale up when the div is bigger than itself? Essentially, I want to use background-size: contain;, but with a max set to the image's height.

I tried all kinds of cover and contains, but none have the desired effect.

This question does not help either, for I cannot set a max-height on the div. It contains content added by the site's editor. If that's a lot, all of it must show.

Here's a fiddle: http://jsfiddle.net/Bakabaka/2zetkrg0/


Solution

  • Is simply inserting an img inside the element you wanted to give a background to an option?

    You can use max-width:100%; max-height:100%; on the image, so it will not exceed the container dimensions, but will still retain its aspect ratio and won't grow larger than its original size. Next, you could position the image absolutely and give it z-index:-1 so it'll be behind all the content and won't be affected by it. Finally, just give the image top:50%; left:50%; transform:translate(50%,50%); if you want it centered within its container.

    Here's a demo: https://jsfiddle.net/ilpo/9dnqd6bc/1/

    You could even set min-width and min-height, if you wanted to have a minimum size for the background.