HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

CSS Object Fit

The object-fit property is used to specify how an <img> or <video> should be resized to fit its container.


Why is it Important?

Normally, if you set a fixed width and height on an image, the browser might stretch it and ruin the aspect ratio. object-fit allows you to control the cropping and scaling behavior.


Common Values

object-fit: fill Stretched image
object-fit: contain Contained image
object-fit: cover Covered image

Step-by-Step Code Example

Here is how you apply the object-fit property to an image. Imagine you have a container that is 400x300 pixels, but your image is square.

.container {
    width: 400px;
    height: 300px;
}

.container img {
    width: 100%;
    height: 100%;
    /* This makes the image fill the container nicely without stretching */
    object-fit: cover; 
}

Property Breakdown:

  • fill: The default. The image is resized to fill the container, regardless of its aspect ratio (causes stretching).
  • contain: The image is resized to fit inside the container while maintaining its aspect ratio. Letterboxing (empty space) may occur.
  • cover: The image maintains its aspect ratio but is cropped to fill the entire container. This is very popular for hero sections.
  • none: The image is not resized at all.
  • scale-down: The image is scaled down to the smallest version of none or contain.

Tip: You can use object-position alongside object-fit to decide which part of the image is visible when it is cropped (e.g. object-position: top center;).