css - 带有图像子项的 flex 元素无法正确调整其大小

标签 css flexbox

我找到了这篇文章,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/

相关文章:

css - 是否可以显式设置匿名 flex 元素的样式?

html - Flexbox child 的高度不一样

javascript - 如何为动态宽度内容设置动画?

javascript - 选择文本时 Firefox 输入无法滚动

jquery - 无法删除未识别的水平超链接

html - 选择建议后输入背景(图像)被删除

css - Div 背景图像没有出现?图片来源已多次检查

html - 文本溢出省略号和 flex 在 Firefox 上不起作用

html - css - 水平边框缩短的链接列表?

css - Flex 元素没有并排对齐