html - 如何使用 flex-grow 使图像填充 flex 元素?

标签 html reactjs css flexbox

我已经阅读了所有现有的解决方案,其中图像可以填充包含的 div,但我还没有找到填充没有静态尺寸的 div 的解决方案,例如仅由 flex 布局的 div -成长

目前图像会破坏我在容器上设置的 flex-grow 比例。我希望 img 只填充 div 而不是拉伸(stretch) div。

尽量不要内联样式。

是否有现成的 polyfill 或解决方案?

.container {
  display: flex;
  min-height: 300px;
  width: 500px;
  flex: 1;
}

.sub-container {
  flex: 1;
  display: flex;
  flex-direction: row;
}

.sub-container > div {
  flex-grow: 1;
}

.first-container {
  background-color: blue;
}

.second-container {
  background-color: yellow;
}

.second-container>img {
  max-height: 100%;
  max-width: 100%;
  object-fit: scale-down;
}
<div class="container">
  <div class="sub-container">
    <div class="first-container">
      A
    </div>
    <div class="second-container">
      <img src="https://internationalbarcodes.net/wp-content/uploads/2017/04/QR%20code%20example.jpg" />
    </div>
  </div>
</div>

http://jsfiddle.net/jojonarte/tu3nbw4q/

最佳答案

你的代码中有这个:

.sub-container > div {
  flex-grow: 1;
}

好的,这定义了 flex-grow

但是你还没有定义flex-basis .因此,flex-basis 保留其默认值,即:auto (i.e., content-defined) .

这就是您所看到的布局:一个根据内容调整大小的 flex 元素。

换句话说,因为图像的自然尺寸太大(与容器的大小相比),图像占用了所有可用空间,flex-grow 没有效果(它没有可分配的可用空间)。

作为解决方案,将此添加到规则中:

.sub-container > div {
  flex-grow: 1;
  flex-basis: 0; /* new */
}

或者,更有效地:

.sub-container > div {
  flex: 1; /* fg:1, fs:1, fb:0 */
}

revised fiddle

.container {
  display: flex;
  min-height: 300px;
  width: 500px;
}

.sub-container {
  flex: 1;
  display: flex;
  flex-direction: row;
}

/* ADJUSTMENT HERE */
.sub-container > div {
  flex: 1;
}

.first-container {
  background-color: blue;
}

.second-container {
  background-color: yellow;
}

.second-container>img {
  max-height: 100%;
  max-width: 100%;
  object-fit: scale-down;
}
<div class="container">
  <div class="sub-container">
    <div class="first-container">A</div>
    <div class="second-container">
      <img src="https://internationalbarcodes.net/wp-content/uploads/2017/04/QR%20code%20example.jpg" />
    </div>
  </div>
</div>

更多信息:

关于html - 如何使用 flex-grow 使图像填充 flex 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53828005/

相关文章:

javascript - React-google-maps 中带孔的多边形

java - 试图更改 setText() 方法的对齐方式?

html - 响应 : resize background image in div

html - 宽度为百分比的 `position:fixed` 侧边栏?

html - 如何修复我的 React/ElectronJS View 的大小?

css - 修改 Wicket ComponentTag 父级的属性

javascript - 如何使整个背景可点击?

html - 如何使此 div 中的文本垂直展开?

html - 如何使页面内的框居中

javascript - Webpack Hot Module Replacement 即使在设置后仍然需要完全刷新