简体   繁体   中英

CSS : Object Cover doesn't center an image

I'm trying to create a thumbnail grid, that will be used mainly on mobile.

The image size is unknown: it comes from an Input, and size is dependant of the camera on the mobile phone. So I don't know in advance if a photo will be landscape or portrait . And thus the styling for both thumbnails should be identical.

For a landscape image, I want it to be shown the full height and horizontally centered. For a Portrait image I want to show the full width of the image and vertically centered.

LANDSCAPE IMAGE          PORTRAIT IMAGE
                            +++++++
                            +     +
                            +     +
++++++=======++++++         =======
+     =======     +         =======
+     =======     +         =======
+     =======     +         =======
+     =======     +         =======
++++++=======++++++         =======
                            +     +
                            +     +
                            +++++++

== = actual thumbnail = part of the full image that will be shown
+ = full image size

I guess object-fit: cover; would be best fit.

This works for the landscape image (see codepen: The men on the right is not showw, which is expected)

Unfortunately this doesn't work for the portrait image. The width is correctly scaled to the width of the thumb, but the image is not vertically centered. (see codepen: the top of the building is still visible while the man in front disappeared. What I expected is the top of the building no longer visible, and the head if the man completely visible. I could fix this with a translate, but then the same code won't work with the portrait.

See codepen, using Tailwind https://codepen.io/pasdut/pen/MWbzvzX

Update: I don't know in advance if an image wille be portrait or landscape

I am not using Tailwind so I just gonna give you the code that works.

.portrait {
    height: 100% !important;
    min-width: 100%;
    object-fit: cover;
}

In your second image remove whatever in there and use the "portrait" class. It's actually worked for the first image also if it's the effect you want.

If you give the the portrait image height: 100% it will horizontally and vertically center the image in it's container paired with object-fit: cover . You just need to add the h-full tailwind class to the thumbnail #2 <img> element for it have height: 100% . Have a look at the working CodePen demo .

<img class="object-cover min-w-full min-h-full h-full" 
  src="https://dummyimage.com/400x900/472647/ffff00&text=portrait+image">

图像缩略图垂直/水平居中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM