首页 > 解决方案 > 如何在忽略父级设置的高度的情况下停止 flexbox 容器中的图像?

问题描述

在过去的几天里,我认为我遇到的问题与我正在使用的 API 有关,但在偶然发现这篇谈论 flex:1 问题的文章后,我发现事实并非如此。这篇文章解决了这个问题,但没有解决图像的问题是什么?

HTML

<div className="App">
  <div className="box1">
    <img src={image} />
  </div>
  <div className="box2" />
  <div className="box3" />
</div>

文案

.App {
  height: 100vh;
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .box1{
    flex: 1;
    background: blue;
    display: flex;
    flex-direction: column;
img{
  margin: auto;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 300px;
  //try max height 100% breakesit
  //max-height: 100%
  object-fit: cover;
  background-repeat: no-repeat;
}
  }
  
  .box2{
    background: purple;
    height:200px; 
  }
  .box3{
    background: green;
    height: 250px;
  }
}

沙盒

我希望图像占据父 div 高度的 100%,这可能吗?

标签: htmlcssreactjssassflexbox

解决方案


我终于找到了一个合理的解决方法,它不使用背景图像,而是进一步使用 flex box!这是我的解决方案:

HTML

 <div className="App">
      <div className="box1">
        <img src={image} />
      </div>
      <div className="box2" />
      <div className="box3" />
    </div>

事实证明,据我所知,图像有自己独特的 flex-basis 属性,该属性基于与其他所有元素不同的实际大小,并且他们将其用作默认的 flex 属性,它们会从中增长或缩小,因此设置此值到 0( flex-basis:0 ) 使其行为方式与常规元素相同。唯一的问题是图像的高度将保持在 0px,无论百分比设置如何,这可以通过添加flex-grow:1属性来简单地修复

萨斯

.App {
  height: 100vh;
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .box1{
    display: flex;
    width: 100%;
    height: 100%;
    flex-grow: 1;
    flex-basis: 0;
    background: blue;
    overflow: hidden;

    img{
      width: auto;
      height: auto;
      max-width: 100%;
      max-height: 100%;
      object-fit: cover;
      background-repeat: no-repeat;
      margin: auto;
    }
  }
  
  .box2{
    background: purple;
    height:200px; 
  }
  .box3{
    background: green;
    height: 250px;
  }
}

这是一个代码沙箱,供您使用,因为这似乎是一个基本上没有答案的问题,希望它可以帮助一些像我一样苦苦挣扎的人!


推荐阅读