Chris Chris - 6 months ago 18
Javascript Question

object-fit: get resulting dimensions

When using the new CSS feature

, how can I access the resulting dimensions that the browser has chosen by JavaScript?

So let's assume
is 100x200 pixels. The browser page / viewport is 400px wide and 300px high. Then given this CSS code: {
width: 100%;
height: 100%;
object-fit: contain;
object-position: 25% 0;

The browser would now show the image on the very top with correct aspect ration stretching to the very bottom on the second quarter from the left. This results in those image dimensions:

  • width: 150px

  • height: 300px

  • left: 62.5px

  • right: 212.5px

So what JavaScript call (jQuery allowed) would give me those numbers that I've calculated manually?
(Note: the CSS information themselves are not known by the JavaScript as the user could overwrite them and even add stuff like

To play with the code I've created a fiddle:


Thanks to @bfred I didn't have to make the initial method.

Here is an extended (and rewritten) version of his, that does calculate the object-position values as well.

function getRenderedSize(contains, cWidth, cHeight, width, height, pos){
  var oRatio = width / height,
      cRatio = cWidth / cHeight;
  return function() {
    if (contains ? (oRatio > cRatio) : (oRatio < cRatio)) {
      this.width = cWidth;
      this.height = cWidth / oRatio;
    } else {
      this.width = cHeight * oRatio;
      this.height = cHeight;
    this.left = (cWidth - this.width)*(pos/100);
    this.right = this.width + this.left;
    return this;

function getImgSizeInfo(img) {
  var pos = window.getComputedStyle(img).getPropertyValue('object-position').split(' ');
  return getRenderedSize(true,

document.querySelector('#foo').addEventListener('load', function(e) {
  document.getElementById('result').textContent = JSON.stringify(getImgSizeInfo(;
#container {
  width: 400px;
  height: 300px;
  border: 1px solid blue;

#foo {
  width: 100%;
  height: 100%;
  object-fit: contain;
  object-position: 25% 0;
<div id="container">
  <img id="foo" src=""/>
<pre id="result">

Side note

It appears that object-position can have more than 2 values, and when, you need to adjust (or add) which parameter returns the left position value