CSS Object-fit

object-fit property

The object-fit property in CSS is used to specify how an element should resize its content to fit within its container. It determines how the content of an replaced element, such as an image, video, or iframe, should be resized to fit its container box.

Syntax

/* Keyword values */
object-fit: fill;
object-fit: contain;
object-fit: cover;
object-fit: none;
object-fit: scale-down;

/* Global values */
object-fit: inherit;
object-fit: initial;
object-fit: unset;

Values

  • fill: The replaced element is stretched to fill the content box, potentially distorting its aspect ratio.

  • contain: The replaced element is resized to maintain its aspect ratio while fitting within the content box.

  • cover: The replaced element is resized to maintain its aspect ratio while covering the entire content box.

  • none: The replaced element is not resized, preserving its original size.

  • scale-down: The content is sized as if none or contain, whichever results in a smaller concrete object size.

Examples

Example 1: Using object-fit: fill;

img {
  width: 200px;
  height: 150px;
  object-fit: fill;
}

Example 2: Using object-fit: contain;

video {
  width: 300px;
  height: 200px;
  object-fit: contain;
}

Example 3: Using object-fit: cover;

iframe {
  width: 100%;
  height: 400px;
  object-fit: cover;
}

object-position property

The object-position property specifies the alignment of the replaced element within its box.

/* Keyword values */
object-position: center;
object-position: left;
object-position: top right;

/* Length values */
object-position: 50% 50%;
object-position: 10px 20px;

/* Global values */
object-position: inherit;
object-position: initial;
object-position: unset;

Values

  • Keyword values: These include top, bottom, left, right, and center, which specify the position of the content within the container.

  • Length values: These include lengths such as 10px, 50%, etc., which specify the position of the content relative to the top-left corner of the container.

Examples

Example 1: Using Keyword Values

img {
  width: 200px;
  height: 150px;
  object-fit: cover;
  object-position: center;
}

Example 2: Using Length Values

video {
  width: 300px;
  height: 200px;
  object-fit: contain;
  object-position: 50% 50%;
}

Conclusion

In summary, the object-fit and object-position properties in CSS offer powerful capabilities for adjusting the display and alignment of replaced elements like images, videos, or iframes within their container boxes.

Understanding these properties enables developers to effectively control how content is resized and positioned, ensuring optimal layout and visual presentation across different devices and screen sizes.

Last updated

Was this helpful?