Search code examples
javascriptjquerycssobject-fit

set css object-position property programmatically


I am using the object-fit and object-position css properties to control the placement of an image in css. I want to programmatically set that position with javascript. I tried:

const panPos = 50;
document.querySelector('.image').style.objectPosition = `${panPos}% 0%`;

and nothing happens.

I can console log element.style and I see an objectPosition property, but setting it seems to have no effect.

Please note I am not talking about the position property (absolute, relative, etc).

I can also set this property with jquery using:

$('.image').css({
      'object-position': `${panPos}% 50%`  
    });

but I want to avoid jQuery. Any ideas?


Solution

  • You need to set object-fit to none as well. They are used together, otherwise, object-position gets ignored. So:

    const panPos = 50;
    document.querySelector('.image').style.objectFit = 'none';
    document.querySelector('.image').style.objectPosition = `${panPos}% 0%`;
    

    For more info, refer to: