CSS `object-fit` Property

The `object-fit` property defines how an element's content should be resized to fit its container. It is commonly used with `<img><video> <and> <canvas> elements to control their fitting behavior.

Common Values for `object-fit`

  • `fill`: The content stretches to fill the container. This may distort the content if the aspect ratio of the container is different from the content.
  • `contain`: The content scales to fit the container while maintaining its aspect ratio. The entire content will be visible, but there might be empty space in the container.
  • `cover`: The content scales to cover the entire container while maintaining its aspect ratio. This might cause some of the content to be clipped if the aspect ratio of the container and the content are different.
  • `none`: The content does not resize to fit the container. It maintains its original size.
  • `scale-down`: The content is sized as `none` or `contain`, whichever results in a smaller content size.

Examples of `object-fit` Values

Example: `fill`


/* Object Fit Fill Example */
.object-fit-fill {
    object-fit: fill;
    width: 100%;
    height: 300px;
}

            
Fill Example

Example: `contain`


/* Object Fit Contain Example */
.object-fit-contain {
    object-fit: contain;
    width: 100%;
    height: 300px;
}

            
Contain Example

Example: `cover`


/* Object Fit Cover Example */
.object-fit-cover {
    object-fit: cover;
    width: 100%;
    height: 300px;
}

            
Cover Example

Example: `none`


/* Object Fit None Example */
.object-fit-none {
    object-fit: none;
    width: 100%;
    height: 300px;
}

            
None Example

Example: `scale-down`


/* Object Fit Scale-Down Example */
.object-fit-scale-down {
    object-fit: scale-down;
    width: 100%;
    height: 300px;
}

            
Scale-Down Example

Explanation of CSS Properties

- `object-fit: fill;`: Stretches the content to fill the container, potentially distorting it.
- `object-fit: contain;`: Scales the content to fit within the container while preserving its aspect ratio. The entire content is visible, but there may be gaps in the container.
- `object-fit: cover;`: Scales the content to cover the container, potentially clipping the content. It maintains the aspect ratio but may cause parts of the content to be cut off.
- `object-fit: none;`: Displays the content in its original size, which may cause overflow if the content is larger than the container.
- `object-fit: scale-down;`: Resizes the content as either `none` or `contain`, depending on which results in a smaller size.