简体   繁体   English

CSS 如何在图像宽度更大时填充 div 宽度,当图像高度更大时如何填充高度

[英]How to fill up div width when image width is more and height when image height is more with CSS

Is there a way to fill up a div's height when its containing image's height is more than its width and vice versa with only CSS without extending the image's box.有没有一种方法可以在包含图像的高度大于其宽度时填充 div 的高度,反之亦然,只有 CSS 而不扩展图像的框。

I've made a codepen to explain it better我做了一个代码笔来更好地解释它

https://codepen.io/boidu/pen/xxPYvQV https://codepen.io/boidu/pen/xxPYvQV

.img-container{
    height: 15rem;
    width: 15rem;
    img{
        height: 100%;
        width:100%;
        object-fit: contain;
    }
}

You have to give height and width separately to the img and set display flex as below for the div containing img您必须分别为 img 提供高度和宽度,并为包含 img 的 div 设置 display flex

display: flex;
flex-direction: row;
align-items: center;
justify-content: center;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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