我找到了这篇文章,Flex item with image child doesn't adjust from its original width ,我最初认为它有答案,但它没有,......当使用设定高度时,它部分地做到了。
我想要并期望在这里发生的是图像与文本元素的高度相匹配,然后在保持其比例的同时调整其宽度。
这似乎在 Chrome 中有效,但在 Edge/IE/Firefox 中无效。由于我没有 iOS 设备,因此无法测试 Safari,所以如果有人可以分享它如何/是否可以在那里工作,我将不胜感激。
这不需要是 flexbox
解决方案,但我希望是 CSS 解决方案,这意味着没有脚本。
编辑
给定文本的高度可以是动态的,并且基于它的内容,所以预定义的 200px
只是给它一个高度,JSFiddle demo, set height .
JSFiddle demo, content based height
堆栈片段
.container {
display: inline-flex;
}
.img img {
height:100%;
}
.text {
background: lightblue;
}
.text-content {
width: 200px;
}
<div class="container">
<div class="img">
<img src="http://placehold.it/160x90">
</div>
<div class="text">
<div class="text-content">
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
</div>
</div>
</div>
预期结果(硬编码)
.container {
display: inline-flex;
}
.img img {
height:100%;
width: 355px; /* force correct width */
}
.text {
background: lightblue;
}
.text-content {
width: 200px;
}
<div class="container">
<div class="img">
<img src="http://placehold.it/160x90">
</div>
<div class="text">
<div class="text-content">
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
Some text content<br>
</div>
</div>
</div>
最佳答案
您应该在 .container
级别定义高度。以下 CSS 将适用于您上面提到的所有浏览器:
.container {
display: inline-flex;
height: 200px;
}
.img {
height: 100%;
}
.img img {
height:100%;
}
.text {
background: lightblue;
}
.text-content {
width: 200px;
}
更新
我会保留旧答案以防万一,但这似乎有效 codepen . 我试过不同的行数和文字大小。
.container {
display: inline-flex;
}
.img img {
height:100%;
}
.text {
background: lightblue;
}
关于css - 带有图像子项的 flex 元素无法正确调整其大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43185407/