Search code examples
javascriptjquerycssviewport

How to get contain size width and height?


Suppose I have the following html:

html,body{
    height: 100%;
    overflow-y: hidden;
}
div{
    background: url(path) no-repeat center;
    width: 100%;
    height: 100%;
    background-size: contain;
}

demo

Here, the background-size is contain and is full width and height of 100% but the area of background image is not fully covered by the div.

So, is there any way to get the width and height of the covered image?

enter image description here


Solution

  • The documentation mentions the following about contain:

    This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.

    That would work out to the following code (ES6):

    function contain({width: imageWidth, height: imageHeight}, {width: areaWidth, height: areaHeight}) {
      const imageRatio = imageWidth / imageHeight;
    
      if (imageRatio >= areaWidth / areaHeight) {
        // longest edge is horizontal
        return {width: areaWidth, height: areaWidth / imageRatio};
      } else {
        // longest edge is vertical
        return {width: areaHeight * imageRatio, height: areaHeight};
      }
    }
    
    console.log(1, contain({width: 15, height: 60}, {width: 20, height: 50}));
    console.log(2, contain({width: 15, height: 60}, {width: 50, height: 20}));
    console.log(3, contain({width: 60, height: 15}, {width: 20, height: 50}));
    console.log(4, contain({width: 60, height: 15}, {width: 50, height: 20}));
    console.log(5, contain({width: 40, height: 20}, {width: 50, height: 20}));

    Depending on the image orientation (portrait or landscape) it grows the longest edge first, then shrinks the shortest edge where necessary while still preserving the aspect ratio.