39

I set my background image to contain:

.el {
    background: url(path/to/img.jpg) no-repeat center center;
    background-size: contain;
}

But that scales the image up. I want the image to never be bigger than its native dimensions, and only scale down when it won't fit at its native resolution.

Here's a demo: http://jsfiddle.net/6W3yh/


I'm looking for a solution in CSS only.
No JavaScript please.

9
  • One alternative is to use CSS media queries to adjust your image's dimensions based on different screen sizes that are relative to your image size.
    – klewis
    Mar 12, 2013 at 14:18
  • @blachawk - I understand that, but I'm trying to avoid that for multiple reasons, not least of which is that I'll have to update my media queries whenever the image (dimensions) is updated :(
    – MegaHit
    Mar 12, 2013 at 14:20
  • That may not be true if you decide to experiement with percentages...In theory your future images should fit.
    – klewis
    Mar 12, 2013 at 14:25
  • @blachawk - I did try, but I couldn't get it to work. Can you show me how it's done? I added a fiddle to my question.
    – MegaHit
    Mar 12, 2013 at 14:27
  • Use max-width:(your max img width) to your .el
    – otinanai
    Mar 12, 2013 at 14:30

6 Answers 6

6

Unfortunately, what you want to do isn't possible in CSS.

Your best bet is to set the background-size using Javascript. However, if you want the image to scale down if the container is smaller than it, you will have to be able to retrieve the image's natural height.

if ($('.el').height() < imageHeight) {
  $('.el').css('background-size', 'contain');
}
else {
  $('.el').css('background-size', 'auto');
}
4
  • I know how to do it in JS. I'm looking for a CSS only solution. Is this not a common need? Why isn't this addressed in the CSS3 background-size property?
    – MegaHit
    Mar 12, 2013 at 18:56
  • 1
    As far as I know, there is no CSS only solution to this. w3schools.com/cssref/css3_pr_background-size.asp
    – Bill
    Mar 13, 2013 at 10:54
  • @MegaHit I agree this would be very useful, but it is impossible with CSS as it stands in 2014. Javascript or bust, I'm afraid.
    – aaaidan
    Sep 19, 2014 at 3:23
  • Example of the above technique in vanilla JS. codepen.io/tommybickerdike/pen/xxrNzVo Oct 21, 2022 at 13:22
3

You could use Uncle Dave's Ol' Padded Box Technique for this. Here's a fiddle showing it in action.

div {
    background: url(http://cdn4.iconfinder.com/data/icons/silent_night_icons/128/santa.png) no-repeat center center;
    background-size: 100%;

    width: 100%;
    max-width: 128px;
    height: 0;
    padding-bottom: 100%; /* (Image Height / Image Width) * 100%; */
}

The only problem is that you'll need to know the width of your image for this to work. If you're using a CSS preprocessor like Compass you could offload this work onto the processor instead of doing it manually. Look here for information on that.

3
  • I don't want to scale my container according to the image. I want the image to scale with the container.
    – MegaHit
    Mar 13, 2013 at 5:03
  • 1
    Not sure I'm fully following what you want. Is this more in line with what you're thinking? Fiddle. If you used an img instead of a CSS background you could do away with the inner div.
    – kpeatt
    Mar 13, 2013 at 17:22
  • @kpeatt the solution in you comment was exactly what I was looking for and solves the problem pretty fine :) Sep 30, 2015 at 13:27
2

You may use this JQuery fix:

$('.target').each(function() {
        if ($(this).css('background-size') == 'contain') {
            var img = new Image;
            var currObj = $(this);
            img.src = currObj.css('background-image').replace(/url\(|\)$/ig, "").replace(/"/g, "").replace(/'/g, "");
            img.onload = function(){
                if (img.width < currObj.width() && img.height < currObj.height()) {
                    currObj.css('background-size', 'auto auto');
                }
            }
        }
    }); 
1
  • 4
    Welcome to SO! Try to provide more explaination to your answers. See How to answer page for help in improving your answer.
    – Madness
    Aug 6, 2015 at 22:12
1

To get the natural width / height, you could put the background image in the html and hide it, then grab the image width / height with script.

HTML:

<div></div>
<img id="background" style="display: none" src="http://cdn4.iconfinder.com/data/icons/silent_night_icons/128/santa.png" />

JS:

var backgroundSize = $('#background').css('width');
1

I use two approaches:

1 - Object-Fit

This has good browser support: https://caniuse.com/#feat=object-fit

.container {
  position: relative;
  width: 200px;
  height: 200px;
  /* Just for style */
  display: inline-block;
  background: rgba(0,0,0,0.2);
  margin: 10px;
}
.container img {
  width: 100%;
  height: 100%;
  object-fit: scale-down;
}
<div class="container">
  <img src="https://picsum.photos/300/200">
</div>

<div class="container">
  <img src="https://picsum.photos/200/300">
</div>

<div class="container">
  <img src="https://picsum.photos/100/100">
</div>

2 - Position and Transform

When you need to target older browsers, this works equally well with no change to your markup

.container {
  position: relative;
  width: 200px;
  height: 200px;
  /* Just for style */
  display: inline-block;
  background: rgba(0,0,0,0.2);
  margin: 10px;
}
.container img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 100%;
  max-height: 100%;
}
<div class="container">
  <img src="https://picsum.photos/300/200">
</div>

<div class="container">
  <img src="https://picsum.photos/200/300">
</div>

<div class="container">
  <img src="https://picsum.photos/100/100">
</div>

0

CSS Solution: You need to know the height and width of the image.

@media screen and (max-width: 640px) and (max-height: 480px) {
    div {
        background-size: contain !important;
    }
} 

div {
    background: #000 url('https://i.imgur.com/someimage.jpg') no-repeat center center;
    background-size: 640px 480px;
}

Where the image url is https://i.imgur.com/someimage.jpg and the width and height of the image is 640px and 480px respectively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.