简体   繁体   中英

Image resize in CSS working on Safari but not on Google Chrome

I've been trying to square photos with CSS (code below). For some reason, it won't work on Google Chrome (but it works on Safari). Does anyone know how to fix this?

CSS code:

img {
    width: 300px;
    height: 300px;
    object-fit: cover;
}

Result on Safari:

关联

Result on Google Chrome:

关联

You can put those images in a parent tag like article and then apply width & height to your parent tag( article ). Then set the images width & height to 100% so the image fits the parent(article) completely.

This way: as you can see that the photo width is 500px but the parent doesn't let it Grow and occupy more space.

https://picsum.photos/500 width: 500px.

 .container { display: flex; width: 400px; height: 100px; } article { width: 100px; height: 100px; } article img { width: 100%; height: 100%; border: 1px solid red }
 <section class="container"> <article> <img src="https://picsum.photos/500"> </article> <article> <img src="https://picsum.photos/500"> </article> <article> <img src="https://picsum.photos/500"> </article> <article> <img src="https://picsum.photos/500"> </article> </section>

No matter if your images ratio is 16:9 or 1 .

 .container { display: flex; width: 400px; height: 100px; } .container article { width: 100px; height: 100px; } .container article img { width: 100%; height: 100%; border: 1px solid red }
 <p> The width = 200 px and the height: 500 px</p> <section class="container"> <article> <img src="https://picsum.photos/200/500"> </article> <article> <img src="https://picsum.photos/200/500"> </article> <article> <img src="https://picsum.photos/200/500"> </article> <article> <img src="https://picsum.photos/200/500"> </article> </section><br> <p>The same image you can see</p><br> <img src="https://picsum.photos/200/500">

This isn't an answer to the problem because I can't see that there is a problem but I thought it might be useful to put up a snippet which you can try on your version of Chrome to see if you are still experiencing the problem.

This snippet takes images, two of them square and one portrait and one landscape aspect ratio. As you can see they are cropped top and bottom or at the sides as appropriate to make them fit and cover the 300x300 squares. There is no distortion.

 img { width: 300px; height: 300px; object-fit: cover; }
 <img src="https://picsum.photos/id/1049/1024/768"/> <img src="https://picsum.photos/id/1049/768/768"/> <img src="https://picsum.photos/id/1049/768/1024"/> <img src="https://picsum.photos/id/1049/1024/1024"/>

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