Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 371
Bhojendra Rauniyar Avatar asked Jun 10 '14 04:06

Bhojendra Rauniyar


People also ask

How do you find the height or width?

The Graphics' industry standard is width by height (width x height). Meaning that when you write your measurements, you write them from your point of view, beginning with the width.

How do you find the height and width of a canvas?

You can get the width and height of a canvas element simply by accessing those properties of the element. For example: var canvas = document. getElementById('mycanvas'); var width = canvas.


1 Answers

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.

like image 108
Ja͢ck Avatar answered Oct 11 '22 04:10

Ja͢ck