gpt4 book ai didi

css - 如何缩小 img 以适应其 flex 容器?

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:10 39 4
gpt4 key购买 nike

在此JSFiddle我怎样才能将 img/img-container 缩小到与其最宽的兄弟 div 一样宽?

.outer {
display: inline-flex;
flex-flow: column;
}

.outer span {
display: flex;
}

div {
border: 1px dotted black;
}
<div class="outer">
<div>
<span>text</span>
<span>more text</span>
</div>

<div>
<img src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded">
</div>

<div>
<span>this should determine width</span>
</div>
</div>

最佳答案

我不确定这个解决方案的跨浏览器兼容性如何,但它适用于 Chrome 64、Safari 11 和 Firefox 57。

给包含 img 的元素一个 width: 0;最小宽度:100%; max-width: 100%;img 本身是一个 width: 100%;

像这样:

div {
border: 1px dotted black;
}

.outer {
display: inline-flex;
flex-flow: column wrap;
}

.child {
width: 0;
min-width: 100%;
max-width: 100%;
}

.img {
width: 100%;
}
<div class="outer">
<div>
<span>text</span>
<span>more text</span>
</div>

<div class="child">
<img class="img" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" />
</div>

<div class="main">
<span contenteditable>this should determine width</span>
</div>
</div>

另一种解决方案

使用 background-image 而不是 img。这允许我们使图像与 flexbox 中最宽元素的宽度一起缩放。

诀窍是在元素上设置一个 padding-bottom,图像与图像比例成正比。在这种情况下,图像是正方形的,所以我将设置 `padding-bottom: 100%;所以它创建了一个方形元素。

如果图像是宽矩形,200 x 100 像素,我会设置 padding-bottom: 50%。或者,如果图像是一个高矩形,100 x 200 像素,我会设置 padding-bottom: 200%

像这样:

div {
border: 1px dotted black;
}

.outer {
display: inline-flex;
flex-flow: column wrap;
}

.img {
background-image: url(https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded);
background-repeat: no-repeat;
background-size: cover;
padding-bottom: 100%;
}
<div class="outer">
<div>
<span>text</span>
<span>more text</span>
</div>

<div class="img">
</div>

<div>
<span contenteditable>this should determine width</span>
</div>
</div>

关于css - 如何缩小 img 以适应其 flex 容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48830306/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com