首页 > 解决方案 > 图像未采用父母身高

问题描述

我有以下内容html

<div class='fullHeight'>
  <div class='flexbox'>
    <div class='first'>
      <p>foo</p>
    </div>
    <div class='second'>
      <p>bar</p>
      <img src='http://www.mandysam.com/img/random.jpg'>
    </div>
  </div>
</div>

css

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.fullHeight {
  height: 100vh;
  background-color: red;
}
.flexbox {
  display: flex;
  flex-direction: column;
  height: 100%;
  maxHeight: 100%;
  width: 100%;
  background-color: green;
}
.first {
  background-color: magenta;
}
.second {
  background-color: yellow;
  flex: 1 1 auto;
  max-height: 100%;
  height: 100%;
  widht: auto;
}

只要没有图像,一切正常:

在此处输入图像描述

但是只要一张图片进来,它就会溢出容器,而不是被缩小以适应可用的高度:

在此处输入图像描述

密码笔

标签: htmlcssflexbox

解决方案


你错过了

display: flex;
flex-direction: column;

在您的.second班级中,这就是该flex物业没有做任何事情的原因。它也应该是max-height代替maxHeightwidth代替widht

您可以将background-image其用于您的目的。

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.fullHeight {
  height: 100vh;
  background-color: red;
}
.flexbox {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: green;
}
.first {
  background-color: magenta;
}
.second {
  background-color: yellow;
  display: flex;
  flex-grow: 1;
  flex-direction: column;
 }
.container {
  background-color: green;
  flex-grow: 1;
  background-image: url('http://www.mandysam.com/img/random.jpg');
  background-size: contain;
  background-repeat: no-repeat;
}
<div class='fullHeight'>
  <div class='flexbox'>
    <div class='first'>
      <p>foo</p>
    </div>
    <div class='second'>
      <p>bar</p>
      <div class="container">
      </div>
    </div>
  </div>
</div>


推荐阅读