Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 890
mheavers Avatar asked Apr 09 '26 10:04

mheavers


1 Answers

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:

  • https://css-tricks.com/almanac/properties/o/object-position/
  • https://codepen.io/robinrendle/pen/raGOOJ
like image 183
Eye Avatar answered Apr 11 '26 23:04

Eye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!