JavaScript - fill/cover with image all div container keeping image ratio

3 points
Created by:

In this article we are going to show how in JavaScript fill with image all div to cover all available space keeping image ratio.

Note: for pure CSS version with img element read this article.

CSS with JavaScript conditional styling example

In this section we select one case of styling depending on containing div and image ratio to fill all available div space and do not lose image ratio, centering image vertically and horizontally.

The effect is similar to background-size: cover; but with additional image centering.

Note: it is important to set container size in this example.

// ONLINE-RUNNER:browser;

<!doctype html>

    #container1 { border: 1px solid red; width: 120px; height: 200px; }
    #container2 { border: 1px solid red; width: 300px; height: 120px; }

  <div id="container1">
    <img id="image1" src="">
  <br />
  <div id="container2">
    <img id="image2" src="">

    function centerImage(hContainer, hImage, callback)
    { = 'relative'; = 'hidden'; = 'absolute'; = '50%'; = '50%'; = 'translate(-50%, -50%)';

        hImage.addEventListener('load', function()
            var containerWidth = hContainer.offsetWidth;
            var containerHeight = hContainer.offsetHeight;
            var pictureWidth = hImage.offsetWidth;
            var pictureHeight = hImage.offsetHeight;

            var containerRadio = containerWidth / containerHeight;
            var pictureRadio = pictureWidth / pictureHeight;

            if(containerRadio > pictureRadio)
       = '100%';
       = '100%';
       = '100%';
       = 'auto';
       = 'none';
       = 'none';
       = 'auto';
       = 'none';
       = 'none';
       = '100%';
       = '100%';
       = '100%';


        hImage.addEventListener('error', function()

    // Usage example:

    var container1 = document.querySelector('#container1');
    var container2 = document.querySelector('#container2');
    var image1 = document.querySelector('#image1');
	var image2 = document.querySelector('#image2');

    centerImage(container1, image1);
	centerImage(container2, image2);


Used resource:

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂