It works like the cover value, but it doesn’t respect its container’s aspect ratio. In this case, the image won’t be resized at all, neither stretched nor squeezed. When using object-fit: fill, the image will be squeezed, stretched, or resized accordingly. With this, the image will be resized to fit the aspect ratio of its container, and if the image’s aspect ratio doesn’t match the container’s, it will be either squeezed or stretched. When using object-fit: cover, the image will be either clipped to fit or resized accordingly. Here, the image will also be resized to fit the aspect ratio of its container, and if the image’s aspect ratio doesn’t match the container’s, then it will be clipped to fit. When using object-fit: contain, the image will be either letterboxed or resized accordingly. If the image’s aspect ratio doesn’t match the container’s, it will be letterboxed. In this case, the image will be resized to fit the aspect ratio of its container. Possible Values for object-fit object-fit: contain The default value for object-fit is fill, which can result in an image being squeezed or stretched. The object-fit property defines how the content of a replaced element such as img or video should be resized to fit its container. ( Spoiler alert: It’s easier!) CSS object-fit Now that we understand how that works, let’s get into how this works in the browser. This retains the image’s aspect ratio and prevents it from being squeezed. Before diving into CSS solutions, I want to show you how we used to do this in photo-editing apps: First, we would center the image vertically, and then clip in a mask. We don’t always need to add a different-sized image when the aspect ratio of the image doesn’t align with the containing element’s width and height. We see this in the following figure: The image’s aspect ratio is different than the containing box, and the image gets stretched. If the image’s aspect ratio is different than the width and height specified for it, then the result will be either a squeezed or stretched image. ( Large preview)Īn image will have an aspect ratio, and the browser will fill the containing box with that image. Consider the following figure: A good-looking photo that gets squeezed when used in a card component. That isn’t good, and it can be solved either with object-fit for an img element or by using background-size.įirst, let’s define the problem. If we use a width and height that isn’t proportional to the image’s aspect ratio, the image might either be compressed or stretched. We’re not always able to load different-sized images for an HTML element. In this article, we will go through how object-fit and background-size work, when we can use them, and why, along with some practical use cases and recommendations.
0 Comments
Leave a Reply. |