flex-row 布局中的图像忽略它的分配高度

Posted

技术标签:

【中文标题】flex-row 布局中的图像忽略它的分配高度【英文标题】:Image in flex-row layout ignores it’s allocated height 【发布时间】:2022-01-09 10:36:10 【问题描述】:

我想要一个包含图像和标题的容器。 容器的大小应始终相同,标题高度可能会发生变化。

在我看来,标题应该获得自动高度,具体取决于它的大小,其余的容器高度将分配给图像。

我尝试使用 div 来做到这一点,但我的工作完美无缺。当我将占位符 div 与实际的图像标签交换时,图像将占用容器的 100% 高度,而不是容器中分配的弹性空间。

为什么会这样,我该如何解决?

显示 div 和 image 标记之间区别的示例: https://codepen.io/lkssmnt-the-lessful/pen/QWqbxNK?editors=1100

.project 
  height: 500px;
  width: 500px;

  display: flex;
  flex-direction: column;


.project img 
  height: 100%;
  width: 100%;
  object-fit: cover;

【问题讨论】:

【参考方案1】:

overflow: hidden 添加到.img 标记。 - 但是,这具有剪断图像底部的负面影响。

* 
  margin: 0;
  padding: 0;
  box-sizing: border-box;


.wrapper 
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;


.project 
  height: 500px;
  width: 500px;
  border: 5px solid red;
  margin: 1rem;

  display: flex;
  flex-direction: column;


.project p 
  padding: 1rem;


.project img 
  overflow: hidden;
  height: 100%;
  width: 100%;
  
  object-fit: cover;


.project .test 
  height: 100%;
  width: 100%;
  background: beige;
<div class="wrapper">
  
  <div class="project">
    <div class="test"></div>
    <p>Project 1</p>
  </div>
  
  <div class="project">
    <img src="https://images.unsplash.com/photo-1518676590629-3dcbd9c5a5c9?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=987&q=80">
    <p>Project 2</p>
  </div>
  
  
</div>

【讨论】:

以上是关于flex-row 布局中的图像忽略它的分配高度的主要内容,如果未能解决你的问题,请参考以下文章