Javascript DOM CSS Style objectPosition Property

Introduction

Resize an image to fit its content box, and position the image 5px from the left and 10% from the top inside the content box:

document.getElementById("myImg").style.objectPosition = "0 10%";

Click the button to change the object-position of the image:

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myImg {//  w w  w. j av  a2 s.com
  width: 200px;
  height: 400px;
  object-fit: cover;
  border: 5px solid red;
}
</style>
</head>
<body>
<h1>Change objectOosition with JavaScript</h1>


<img src="image3.png" alt="Paris" id="myImg" width="400" height="300">
<br>

<button onclick="myFunction()">Test</button>
<script>
function myFunction() {
  document.getElementById("myImg").style.objectPosition = "0 10%";
}
</script>

</body>
</html>

The objectPosition property is used to specify how an <img> or <video> should be positioned in its own content box.

Property Values

Value
Description
position



Sets the position of the image or video inside its content box.
First value controls the x-asis and the second value controls the y-axis.
Can be a string (left, center or right), or a number (in px or %).
Negative values are allowed
initial
Sets this property to its default value.
inherit
Inherits this property from its parent element.

The objectPosition property Default Value: 50% 50%

The objectPosition property returns a String or a Number representing the position of an element in its content box.




PreviousNext

Related