【问题标题】:how to stop images within a flexbox container ignoring the heigth set by parent?如何在忽略父级设置的高度的情况下停止 flexbox 容器中的图像?
【发布时间】:2021-01-05 12:33:03
【问题描述】:

在过去的几天里,我认为我遇到的问题与我正在使用的 API 有关,但在偶然发现这个 article talking about flex:1 issues 之后,我发现它不是。 文章解决了这个问题,但没有解决图像问题?

HTML

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

Scss

.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;
  }
}

Sandbox

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

【问题讨论】:

    标签: html css reactjs sass flexbox


    【解决方案1】:

    我终于找到了一个合理的解决方法,它不使用背景图片,而是进一步使用 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;
      }
    }
    

    这里有一个code sandbox 演示供您使用,因为这似乎是一个基本上没有答案的问题,希望它可以帮助一些和我一样苦苦挣扎的人!

    【讨论】:

      【解决方案2】:

      您可以使用您的图像作为 div 的背景

      .box1{
          background-repeat: no-repeat;
          background-size: 100% 100%;
      }
      
      <div className="box1" style={{background: `url(${image})`}}>
      

      【讨论】:

      • 这会严重拉伸图像吗?我希望根据注入的图像的纵横比显示带有顶部或底部边框的完整图像?
      • 您可以调整背景类型。看这篇文章:css-tricks.com/perfect-full-page-background-image
      • 这似乎很有希望我正在沙箱中尝试它,如果它按预期工作,我一定会将它集成到我的项目中!
      • 哇,这是一个很棒的链接,加布里埃尔。我稍后再读。
      猜你喜欢
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 2017-07-30
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多