CSS object-fit

The object-fit property in CSS is used to specify how an image, video, or other media content is resized to fit its container. It ensures that the media content is displayed correctly without distortion.

Key Topics

Fill

The default value, fill, stretches the content to completely fill the container, potentially distorting it.

<style>
        .object-fill {
            width: 300px;
            height: 200px;
            object-fit: fill;
        }
</style>
<img src="example.jpg" alt="Example" class="object-fill">

Explanation: The image is stretched to fill the container completely, which may result in distortion.

Contain

The contain value scales the content to fit inside the container without cropping or distortion.

<style>
        .object-contain {
            width: 300px;
            height: 200px;
            object-fit: contain;
            background-color: #f0f0f0;
        }
</style>
<img src="example.jpg" alt="Example" class="object-contain">

Explanation: The image is scaled to fit inside the container while maintaining its aspect ratio, leaving empty space if necessary.

Cover

The cover value scales the content to fill the container while preserving its aspect ratio. Content may be cropped if needed.

<style>
        .object-cover {
            width: 300px;
            height: 200px;
            object-fit: cover;
        }
</style>
<img src="example.jpg" alt="Example" class="object-cover">

Explanation: The image fills the container, and its aspect ratio is preserved. Parts of the image may be cropped to avoid distortion.

None

The none value retains the original size of the content, which may overflow the container.

<style>
        .object-none {
            width: 300px;
            height: 200px;
            object-fit: none;
        }
</style>
<img src="example.jpg" alt="Example" class="object-none">

Explanation: The image retains its original dimensions and may exceed the container's size.

Scale Down

The scale-down value scales the content down to the smallest size possible, either using none or contain.

<style>
        .object-scale-down {
            width: 300px;
            height: 200px;
            object-fit: scale-down;
        }
</style>
<img src="example.jpg" alt="Example" class="object-scale-down">

Explanation: The image is scaled down to the smallest size while maintaining its aspect ratio and avoiding distortion.

Key Takeaways

  • Fill: Stretches the content to completely fill the container, which may cause distortion.
  • Contain: Fits the content inside the container without cropping or distortion, preserving aspect ratio.
  • Cover: Scales the content to fill the container while preserving aspect ratio, with possible cropping.
  • None: Retains the content's original dimensions, potentially overflowing the container.
  • Scale Down: Scales the content to the smallest size possible without distortion or overflow.