Object fit


To fix images in our carousel we need to use CSS property called object-fit.

Tailwind has utility classes for this property, so let's have a look at how exactly it works.


How it works:

The object-fit property in Tailwind CSS is used to specify how an image or video should be resized to fit its container. It accepts the following values:

  • contain: Resize the content to stay contained within its container.
  • cover: Resize the content to cover its container.
  • fill: Stretch the content to fit its container.
  • none: Display the content at its original size ignoring the container size.
  • scale-down: Display the content at its original size but scale it down to fit its container if necessary.

You can use these values to create different effects with your images and videos. For example, you could use contain to ensure that an image always fits within its container, even if it is resized. Or, you could use cover to make sure that an image always fills its container, even if it is cropped.

Let's have a look at an example.

Here we have a square-shaped container with fixed height and width using classes .h-64 and .w-64.

And here we have a rectangular image stretched to full width and height using the .w-full and .h-full classes.

The container and the image have completely different shapes - one is square and the other is rectangular.

How to put an image in a container without distorting it?


If we simply put one into the other, the picture will be distorted.

However, if we add an object-cover class to the image, the image will be scaled to maintain its aspect ratio while completely covering the content box of its container.

In other words, the image will be enlarged or reduced as necessary to cover the entire available space, potentially cropping parts of the image if the aspect ratios don't match.

Now the image in the container looks good, but it may happen that as a result of using .object-cover those parts of the image that we wanted were cropped.

We can improve this with the Object position property and we will do it in the next lesson.



John Doe

About author

Michal Szymanski

Co Founder at TW Elements and MDBootstrap / Listed in Forbes „30 under 30" / Open-source enthusiast / Dancer, nerd & book lover.

Author of hundreds of articles on programming, business, marketing and productivity. In the past, an educator working with troubled youth in orphanages and correctional facilities.