Search code examples
javascriptcsstwitter-bootstrapbackground-size

How to add background-size in css based on image size?


I am working on a project where the user will be able to select or upload an image and it will be displayed inside of these circles. The images are dynamically being added as background-images. The problem comes in when I am trying to set the background-size. If the image is larger than the circles, I would like it to have a background-size cover, so it scales down. If the image is smaller than the circle, I don't want it to scale up or anything so setting no background size achieves this effect.

Any ideas on how I could achieve this?

The main html looks like this:

<div class="image-boundary">
    <div class="content">
        <div class="image-boundary-photo img-responsive" style="background-image: url('https://www.fillmurray.com/g/100/100');" alt="">
        </div>
    /div>
</div>

css:

.module-list-home .content .image-boundary-photo {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  text-align: center;
  background-repeat: no-repeat;
  background-position: center;
}

Here is the codepen of my example. http://codepen.io/johnsonjpj/pen/zKyGZp?editors=1100 The third image should have a background-size: cover; because it is bigger while the others should stay the way they are.


Solution

  • Try this

    $('.img-responsive').each(function(key, el) {
        var img = new Image;
        img.src = $(el).css('background-image').match(/^url\("?(.+?)"?\)$/)[1];
        if ($(el).width() <= img.width || $(el).height() <= img.height)
            $(el).css('background-size', 'cover');
    })
    

    here is a working example