Max size for background image CSS

It's not that hard doing that with CSS

  • 1st, please take a look at the Mozilla Specs for mixed units for background-size.
  • 2nd, please consider simply setting background-size: contain; (IE9+, Safari 4.1+, FF 3.0+, Opera 10+) and min/max-width/height for the container element.

You can absolutely solve this problem without JavaScript using a combination of CSS3 background-size and media-queries. e.g.:

@media only screen and (max-width: 1000px) {
    #element {
        background-size: contain;
    }
}

Note that neither are supported in IE8 or below, so you should include fallbacks for old IE if you still support it.


i'm a little (10 years) late to this question so previous answers weren't good enough for me

we have a css function called clamp which can define size with min & max values: clamp(<min-size>, <expected-size>, <max-size>)

width: clamp(100px, 10vw, 500px);

and yes my friend you can use that for background-size too.

background-size: clamp(1000px, 80%, 1500px) auto;

*IE support is questionable as always.

Tags:

Html

Css

Image