Image object-fit - cover and contain differences
The object-fit
property in CSS is used to control how the content of a replaced element (like an image or video) fits into its container. The cover
and contain
values are two common options, and they have distinct behaviors:
object-fit: cover
- Behavior: The content of the element (like an image) will cover the entire container while preserving its aspect ratio. This means the content will be scaled to fill the container, potentially cropping parts of the content if necessary.
- Usage: This is useful when you want the content to completely cover the container without leaving any empty spaces, even if it means some parts of the content will be cut off.
- Example: For a background image that should fill a container completely without stretching or distorting, even if it means cropping.
img.cover {
object-fit: cover;
width: 100%;
height: 100%;
}
object-fit: contain
- Behavior: The content will be scaled to fit entirely within the container while preserving its aspect ratio. This means the entire content will be visible, but there may be empty space (letterboxing) around it if the aspect ratios of the content and container do not match.
- Usage: This is useful when you want to ensure the entire content is visible within the container without any cropping, even if it means that the content might not completely fill the container.
- Example: For images that should be fully visible within a container, such as a logo or an image in a frame, without any part being cut off.
img.contain {
object-fit: contain;
width: 100%;
height: 100%;
}
Visual Comparison
-
cover
Example:The image fills the container, and the parts that don’t fit within the container’s dimensions are cropped.
-
contain
Example:The image is scaled to fit within the container, and you might see empty space around the edges of the image if it doesn’t exactly match the container’s aspect ratio.
Practical Use Cases
-
object-fit: cover
:- Ideal for background images, hero images, or thumbnails where you want to ensure the image covers the entire area, even if parts are cropped.
- Example: A full-width hero image on a website.
-
object-fit: contain
:- Ideal for images that should be displayed in their entirety, such as icons or logos, where cropping would be undesirable.
- Example: A product image where you need to show the entire product without any part being cropped.
Published on: Jul 19, 2024, 10:36 AM