我发现这篇文章,带有图像子项的 Flex 项目不会从其原始宽度进行调整,我最初认为这是有答案的,但它没有,......当使用设置高度时,部分确实如此。
我想要并期望在这里发生的是图像与文本元素的高度匹配,然后在保持其比例的同时调整其宽度。
这似乎适用于 Chrome,但不适用于 Edge/IE/Firefox。由于我没有 iOS 设备,因此无法测试 Safari,所以如果有人可以分享它如何/是否在那里工作,我将不胜感激。
这不需要是一个flexbox解决方案,尽管我希望有一个 CSS 解决方案,这意味着没有 script。
编辑
给定文本的高度可以是动态的,并且基于其内容,因此预定义200px只是简单地给它一个高度,JSFiddle 演示,设置高度 。
堆栈片段
.container {
display: inline-flex;
}
.img img {
height:100%;
}
.text {
background: lightblue;
}
.text-content {
width: 200px;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
预期结果(硬编码)
.container {
display: inline-flex;
}
.img img {
height:100%;
width: 355px; /* force correct width */
}
.text {
background: lightblue;
}
.text-content {
width: 200px;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
您应该定义水平面的高度.container。以下 CSS 适用于您上面提到的所有浏览器:
.container {
display: inline-flex;
height: 200px;
}
.img {
height: 100%;
}
.img img {
height:100%;
}
.text {
background: lightblue;
}
.text-content {
width: 200px;
}
Run Code Online (Sandbox Code Playgroud)
更新
我会保留旧答案以防万一,但这似乎可以工作codepen。我尝试过不同的行数和文本大小。
.container {
display: inline-flex;
}
.img img {
height:100%;
}
.text {
background: lightblue;
}
Run Code Online (Sandbox Code Playgroud)