Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object-fit: cover; alternative? [duplicate]

Tags:

html

css

image

I have an image on my page that I want to keep the ratio of but resize according to screen size. I would like it so that the smaller of the width and height is made to fit the element exactly, and the larger dimension overflows the element.

I found the

object-fit: cover; 

style which would suit my needs but very quickly found out that support for this is extremely limited (pretty much opera only). Is there anything else I can use to achieve this?

Many thanks in advance :)

like image 371
Dan Avatar asked Oct 31 '13 22:10

Dan


People also ask

What does object-fit cover and object-fit contain mean?

contain - The image keeps its aspect ratio, but is resized to fit within the given dimension. cover - The image keeps its aspect ratio and fills the given dimension. The image will be clipped to fit. none - The image is not resized. scale-down - the image is scaled down to the smallest version of none or contain.

What is object-fit cover?

The object-fit CSS property sets how the content of a replaced element, such as an <img> or <video> , should be resized to fit its container. You can alter the alignment of the replaced element's content object within the element's box using the object-position property.

Why is object-fit contain not working?

For object-fit to work, the image itself needs a width and height . In the OP's CSS, the images do not have width and/or height set, thus object-fit cannot work. ...and the browser will know that this div should completely fill its container's space.


1 Answers

If you're able to add this image to the page as a background, then you can use:

background-size: cover;

This property can also accept contain value. Experiment with both a bit and you'll see the difference.

cover forces the image to fill the whole container. It means the image will be cropped if its ratio doesn't match the container's ratio.
contain forces the image to fit in the container. It means that image will never go out the bounds of the container. If ratios (image and container) are different, there will be blank spaces on the sides of the image (left & right or top & bottom).

cover and contain values are supported accordingly:

Chrome    Firefox   IE    Opera    Safari
3.0       3.6       9.0   10.0     4.1
like image 189
matewka Avatar answered Sep 17 '22 10:09

matewka