Fredy31 Fredy31 - 2 months ago 8
CSS Question

CSS - Background Size Contain or normal

I would like to find some way to have an background-image contained within the div if its larger than the div (background-size:contain;) and if the image is smaller than the div, keep it as it is to not stretch and blur it (background-size:auto;)

Is there any way to do this? I don't have control of the images in the long run, because it's a WordPress website (so images are bound to change, without passing by a programmer)

Answer

  window.onload = function() {

    var imageSrc = document
                    .getElementsByClassName('foo')
                     .style
                      .backgroundImage
                       .replace(/url\((['"])?(.*?)\1\)/gi, '$2')
                        .split(',')[0];

   
    var divWidth = imageSrc.offsetWidth;

    var image = new Image();
    image.src = imageSrc;

    var width = image.width,
        height = image.height;

    alert('width =' + width + ', height = ' + height)
    
    if ( width > divWidth ) {
      
        imageSrc.style.backgroundSize = "contain"; 
      
    }

}

Comments