Javascript DOM CSS Style objectFit Property

Introduction

Cut off the sides of an image, preserving the aspect ratio, and fill in the space:

document.getElementById("myImg").style.objectFit = "cover";

Click the button to cut off the sides of the image, preserving the aspect ratio:

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myImg {/*from   w ww .  j ava2s .c  om*/
  width: 200px;
  height: 400px;
}
</style>
</head>
<body>
<h1>Change objectFit 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.objectFit = "cover";
}
</script>

</body>
</html>

The objectFit property sets how an <img> or <video> should be resized to fit its container.

Property Values

Value Description
fill default. The content is sized to fill the element's content box. If necessary, the object will be stretched or squished to fit
containThe content is scaled to maintain its aspect ratio while fitting within the element's content box
cover The content is sized to maintain its aspect ratio while filling the element's entire content box. The object will be clipped to fit
none The content is not resized
scale-down The content is sized as if none or contain were specified
initialSets this property to its default value.
inheritInherits this property from its parent element.

The objectFit property returns a String representing the object-fit of an element.




PreviousNext

Related