HTML DOM Style objectFit Property


The HTML DOM Style objectFit property returns and modify how an image or video element in an HTML document should be resized to fit its container element.

Syntax

Following is the syntax −

1. Returning objectFit

object.objectFit

2. Modifying objectFit

object.objectFit = “value”

Here, value can be −

ValueExplanation
initialIt set this property value to its default value.
inheritIt inherits this property value from its parent element.
noneIn it the content is not resized.
fillIn it the content is sized to fill the element’s content box and if necessary the object will be stretched or squished to fit the content box.
containIn it the content is scaled to maintain its aspect ratio while fitting within the element’s content box in an HTML document.
coverIn it the content is sized or clipped to maintain its aspect ratio while fitting the element’s entire content box in an HTML document.
scale-downIn it the content is sized.

Let us see an example of HTML DOM Style objectFit Property −

Example

<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      height: 100vh;
      background-color: #8BC6EC;
      background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%);
      text-align: center;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 2px;
      width: 40%;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem auto;
   }
   .img-class {
      width: 200px;
      height: 250px;
   }
</style>
<body>
<h1 style="text-align:center">DOM Style objectFit Property Demo</h1>
<img alt="Learn Time Series" src="https://www.tutorialspoint.com/time_series/images/time-series-mini-logo.jpg" class="img-class" width='300' height='200'>
<button class="btn" onclick="set()">Set objectFit</button>
<script>
   function set() {
      document.querySelector('.img-class').style.objectFit = "contain";
   }
</script>
</body>
</html>

Output

Click on “Set objectFit” button to set object fit property on image element −

Updated on: 23-Sep-2019

39 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements