How to get contain size width and height?

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.