简体   繁体   中英

Restricting the size of an image with both of height and width of parent div

Let's say in my webpage I have a resizable div, in which I have a picture. I'd like the picture to keep its aspect ratio at all times. When resizing the div, I'd like the picture to be the biggest possible, while keeping its aspect ratio. For example, if I have a square image and the div is more wide than tall, the image should take up the full height of the div, while NOT taking up the full width of the div, since it has to keep its aspect ratio. The difficulty comes, when I also want it the other way: when the div is more tall than wide, the image should take up the full width of the div, while not taking up the full height. I can do this with a square picture, but the desired solution would be one that is applicable to arbitrary aspect ratios.

Is this achievable in CSS? (without JS)

Thank you.

You can have a CSS declaration like this:

.some_class {
  width: auto;
  height: auto;
  aspect-ratio: 1 / 1;
}

*Notes that aspect-ratio is not fully supported. Read the documentation here .

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