将图像高度拉伸到剩余空间

时间:2020-06-14 16:13:03

标签: html css

我有固定大小的容器div。在这个容器中,我有:

  • 适合图像(.image-to-fit
  • 其他元素(.other-elements)。

其他元素有一定高度。可以是带有文本,按钮等的div。(其高度与div中所有元素的高度相同),或者在此示例中,它只是具有固定高度的图像。 >

适合显示的图像是我要填充剩余空间的图像。这意味着我要拉伸它而不保留宽高比(宽度是固定的,高度要合适)。

我尝试使用height: autoheight: 100%,但是它不起作用。

下面是示例(结果看起来像我想要的,但在代码中我已将代码硬编码,手动计算得出)。

如果有帮助,您可以在div中包装适合的图像。

.container {
  /* Parent container with fixed height */
  height: 400px;
  width: 100px;
  border: 3px red solid;
  line-height: 0;
}

.image-to-fit {
  width: 100%;
  
  /* What to do for stretch image height (fill the remaining space)? */
  
  /* height: auto not working: */
  /* height: auto; */
  
  /* height: 100% is too high (too high for height of .other-elements) */
  /* height: 100%; */
  
  /* The following two lines are incorrect! It shows how I want the result to look.
     In this example I know height of .other-elements and I can calculate height manually (400px-50px=350px or 100%-12.5%=87.5%),
     but in real world I don't know height of .other-elements (neither px nor %) and I don't want calculate this manually. I want stretch it automatically. */ 
  /* height: 350px; */
  height: 87.5%;
}

.other-elements {
  /* Some fixed height - doesn't matter what is here and I don't know what's height */
  height: 50px;
  width: 100%;
}
<div class="container">
     <img class="image-to-fit" src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/4b/Domestic_Cat_Demonstrating_Dilated_Slit_Pupils.jpg/768px-Domestic_Cat_Demonstrating_Dilated_Slit_Pupils.jpg" />
     <img class="other-elements" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Kittyply_edit1.jpg/1280px-Kittyply_edit1.jpg" />  
</div>

0 个答案:

没有答案