我将 2 张图片放在一个带有列方向的 flexbox 中,我希望在调整浏览器窗口大小时调整图片大小。他们没有像我预期的那样改变。
我希望图像按原始比例改变,但无论我使用什么 css 样式都失败。
当我水平调整窗口大小时效果很好,但当我垂直调整窗口大小时效果不佳。
此外,图片会超出 flexbox div,我该如何防止呢?
#box{
width: 100%;
height: 100%;
}
#container {
display: flex;
flex-direction: column;
width: 50%;
height: 30%;
background-color: red;
}
#photo {
width: 100%;
height: auto;
}
<div id="box">
<div id="container">
<img id="photo" src="1.JPG">
<img id="photo" src="2.JPG">
</div>
</div>
最佳答案
我通常在这种情况下使用的一种方法是使用 css 将图像设置为背景图像并使用 background-size:contain;
一个例子:
#box{
width: 100vw;
height: 100vh;
}
#container {
display: flex;
flex-direction: column;
width: 50%;
height: 30%;
background-color: red;
}
.photo {
width: 100%;
height: 100%;
background-repeat: no-repeat;
background-size:contain;
}
<div id="box">
<div id="container">
<div class="photo" style="background-image: url('https://picsum.photos/200/300/?random')"></div>
<div class="photo" style="background-image: url('https://picsum.photos/300/200/?random')"></div>
</div>
</div>
关于html - flexbox 中的图像无法正确缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51823854/