嵌套的flexbox不会缩小

时间:2019-04-20 16:59:04

标签: html css css3 flexbox

我正在尝试获取可变数量的正方形图像以填充父容器。我需要使图像的尺寸 response 增大或缩小,以确保它们都适合,但决不能在水平方向上超出父容器的尺寸。还需要保留图像比例而不进行裁剪。

我正在尝试使用嵌套的flex-box来完成此任务。 .outer-flex-container可以正常工作,并且所有内容都沿水平轴收缩/增长,同时保持宽高比。

我尝试使用.inner-flex-container获得相同的结果,但沿垂直轴(flex-flow: column)。但是,缩小容器大小时,会得到不缩小(或扭曲宽高比)的图像。

我已经阅读了许多有关使用min-height: 0覆盖默认min-height: auto的文章,但这似乎并不能解决我的问题。

为什么.inner-flex-container不能缩小到容器的大小?有没有比flexbox更好的方法来做到这一点?

.outer-flex-container {
  display: flex;
  flex-flow: row nowrap;
  border: 1px solid red;
  width: 900px;
  height: 500px;
}

.outer-flex-container:hover {
  width: 500px;
  height: 100px;
}

.outer-flex-child {
  flex: 0 1 auto;
  min-height: 0;
  min-width: 0;
}

.inner-flex-container {
  display: flex;
  flex-flow: column nowrap;
  border: 1px solid grey;
  min-height: 0;
  min-width: 0;
  /* max-height: 100%;  <-- Distorts aspect ratio */
  /* max-width: 100%; <-- Distorts aspect ratio */
}

.inner-flex-child {
  flex: 0 1 auto;
  min-height: 0;
  min-width: 0;
  max-height: 100%;
  max-width: 100%;
  opacity: 0.5;
}
<div class="outer-flex-container">
  <div class="outer-flex-child">
    <div class="inner-flex-container">
      <img class="inner-flex-child" src='https://i.stack.imgur.com/QH01k.png' />
    </div>
  </div>

  <div class="outer-flex-child">
    <div class="inner-flex-container">
      <img class="inner-flex-child" src='https://i.stack.imgur.com/QH01k.png' />
    </div>
  </div>

</div>

1 个答案:

答案 0 :(得分:1)

您还可以嵌套Flexbox:

  • 也将您的outer-flex-child用作 flexbox ,并将flex: 0 1 auto添加到其 flex项inner-flex-container)中。

  • ,并且由于您的inner-flex-container列flexbox ,因此将align-items: flex-start添加到 override 默认的 stretch beahvior(align-items: stretch)破坏了图像弹性项目的长宽比。

请参见下面的演示:

.outer-flex-container {
  display: flex;
  flex-flow: row nowrap;
  border: 1px solid red;
  width: 900px;
  height: 500px;
}

.outer-flex-container:hover {
  width: 500px;
  height: 100px;
}

.outer-flex-child {
  flex: 0 1 auto;
  min-height: 0;
  min-width: 0;
  display: flex; /* added */
}

.inner-flex-container {
  display: flex;
  flex-flow: column nowrap;
  border: 1px solid grey;
  min-height: 0;
  min-width: 0;
  flex: 0 1 auto; /* added */
  align-items: flex-start; /* added */
}

.inner-flex-child {
  flex: 0 1 auto;
  min-height: 0;
  min-width: 0;
  max-height: 100%;
  max-width: 100%;
  opacity: 0.5;
}
<div class="outer-flex-container">
  <div class="outer-flex-child">
    <div class="inner-flex-container">
      <img class="inner-flex-child" src='https://i.stack.imgur.com/QH01k.png' />
    </div>
  </div>

  <div class="outer-flex-child">
    <div class="inner-flex-container">
      <img class="inner-flex-child" src='https://i.stack.imgur.com/QH01k.png' />
    </div>
  </div>

</div>

相关问题