简体   繁体   中英

How to keep images in same aspect ratio in CSS when using flexbox?

I've got many images laid out with flexbox. Most of the images have a 2:1 aspect ratio but some don't (can be too wide or too high). I'd like those images to stay within the 2:1 aspect ratio anyway.

In https://jsfiddle.net/5h0gx7L4/ you can see the box that's too wide is fine and stays within the 2:1 aspect ratio (not sure but maybe because flex-basis controls the width), but the one that's too high breaks out of the 2:1 aspect ratio even though it should be contained.

I can't use any hardcoded heights because it's a fluid and responsive design and everything scales up and down as you change the size of the window. But the divs containing the images should have a 2:1 aspect ratio so that any images inside are contained within it and don't get bigger.

 div { display: flex; flex-wrap: wrap; } div > div { flex-basis: 25%; } img { border: 1px solid black; width: 100%; height: 100%; object-fit: contain; } 
 <div> <div><img src=https://placeholder.pics/svg/400x200/FF9A9A></div> <div><img src=https://placeholder.pics/svg/400x200/FF9A9A></div> <div><img src=https://placeholder.pics/svg/800x200/FF9A9A></div> <div><img src=https://placeholder.pics/svg/400x200/FF9A9A></div> <div><img src=https://placeholder.pics/svg/400x200/FF9A9A></div> <div><img src=https://placeholder.pics/svg/400x400/FF9A9A></div> <div><img src=https://placeholder.pics/svg/400x200/FF9A9A></div> </div> 

Try this:

 div { display: flex; flex-wrap: wrap; box-sizing: border-box; } div > div { flex-basis: 25%; display: block; padding-bottom: 12.5%; height: 0; position: relative; } img { border: 1px solid black; max-width: 100%; max-height: 100%; object-fit: contain; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; box-sizing: border-box; } 
 <div> <div><img src="https://placeholder.pics/svg/400x200/FF9A9A"></div> <div><img src="https://placeholder.pics/svg/400x200/FF9A9A"></div> <div><img src="https://placeholder.pics/svg/800x200/FF9A9A"></div> <div><img src="https://placeholder.pics/svg/400x200/FF9A9A"></div> <div><img src="https://placeholder.pics/svg/400x200/FF9A9A"></div> <div><img src="https://placeholder.pics/svg/400x400/FF9A9A"></div> <div><img src="https://placeholder.pics/svg/400x200/FF9A9A"></div> </div> 

You can set the height to zero and use padding-top or padding-bottom for the aspect ratio since it's based on the element's width. In your case it should look like this:

div > div {
  flex-basis: 25%;
  height: 0;
  padding-bottom: 12.5%; /* 25/2 = 2:1 */
}

Updated jsfiddle

Edit: Ignore my answer, see comments and Kravimir's solution

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