简体   繁体   中英

CSS - Dynamically set height and width of img to fit content

What is the best way to dynamically size an image to fit in a div container.

For instance, I want to have a parent container with a max height of 50% and a max width of 100%. I then want to fit an image inside of there. If the image is landscape and is within the max height of the parent container, it should stretch all the way across horizontally, but be as tall as it needs to be. If the image is portrait and is OVER the max height of the parent container, it should stop at max 50% and be as wide as it needs to be depending on the ratio of the photo.

Thank you.

I tried to add a parent div with height: 50% and width: 100%, then I added max-height: 100% and max-width: 100% to the child image. It works fine for photos taller than the 50%, however if the photo is shorter than 50%, that div still takes up 50% regardless and creates ugly whitespace underneath the photo.

Since you don't provides code nor html, all I can say it's you can use object-fit: contain; css property on image's parent to contain image without lose aspect ratio.

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