首页 > 解决方案 > 如何让图像填充 div 内的剩余空间?

问题描述

我有一个<div>占用 60% 的窗口空间,它包含两件事:

如何使用纯 CSS(无 Javascript)来做到这一点?我一直在尝试一堆东西,没有运气。

这是我能得到的最接近的;图像潜入绿色边框之外div.container

html, body {
  height: 100%;
  overflow: hidden;
  margin: 0px;
}
div.container {
  height: 60%;
  border: 2px solid green;
  box-sizing: border-box;
}
div.rest {
  height: 40%;
  border: 2px solid red;
  box-sizing: border-box;
}
div.img-container {
  height: 100%; /* this is wrong, but what do I do? */
}
div.img-container img {
  max-height: 100%;
  max-width: 100%;
  height: auto;
  width: auto;
  opacity: 0.5;
}
<html>
<body>
<div class="container">
<div class="header">hieronymus bosch last judgement</div>
<div class="img-container"><img src="https://i.imgur.com/TT6drhn.jpg"></div>
</div>
<div class="rest">
<h1>blah blah blah</h1>
</div>
</body>
</html>

这是我尝试使用flex但失败了。

html, body {
  height: 100%;
  overflow: hidden;
  margin: 0px;
}
div.container {
  height: 60%;
  border: 2px solid green;
  box-sizing: border-box;
  display: flex;
  flex-direction: column
}
div.rest {
  height: 40%;
  border: 2px solid red;
  box-sizing: border-box;
}
div.img-container {
  flex: 1;
}
div.header {
  flex: 0;
}
div.img-container img {
  max-height: 100%;
  max-width: 100%;
  height: auto;
  width: auto;
  opacity: 0.5;
}
<html>
<body>
<div class="container">
<div class="header">hieronymus bosch last judgement</div>
<div class="img-container"><img src="https://i.imgur.com/TT6drhn.jpg"></div>
</div>
<div class="rest">
<h1>blah blah blah</h1>
</div>
</body>
</html>

标签: htmlcssflexbox

解决方案


如果您div.img-container在 Chrome Inspector 中查看,您可以看到问题所在 -img元素正在完成其工作并填充其容器,但容器本身正在溢出。

发生这种情况是因为它被设置为height: 100%- 这就是说“让我的身高达到我父母身高的 100%”,但这并不意味着“填充剩余的空间”。浏览器只是读取元素父元素的计算高度,然后将其乘以您的 % 值 - 基本上,这都是绝对值。 您可以看到蓝色框的高度是绿色框的 100%,但由于它位于一行文本的下方,因此超出了该文本的高度。

flex可以用来解决这个问题,但是您可以通过使用calc减去该文本的高度来快速修补这个问题。在您的示例中,它是 19px,我建议手动设置该height文本元素容器的 ,以确保在边缘情况下不会中断。然后,.img-container得到height: calc(100% - 19px)它并按预期工作。

html, body {
  height: 100%;
  overflow: hidden;
  margin: 0px;
}
div.container {
  height: 60%;
  border: 2px solid green;
  box-sizing: border-box;
}
div.rest {
  height: 40%;
  border: 2px solid red;
  box-sizing: border-box;
}
div.img-container {
  height: 100%; /* this is wrong, but what do I do? */
}
div.img-container img {
  max-height: 100%;
  max-width: 100%;
  height: auto;
  width: auto;
  opacity: 0.5;
}

/* 
  ADDED CODE BELOW
*/

/* optional, just to be safe */
.header {  
  height: 19px;
}

/* overrides .img-container from above */
.img-container {
  height: calc(100% - 19px) !important;
}
<html>
<body>
<div class="container">
<div class="header">hieronymus bosch last judgement</div>
<div class="img-container"><img src="https://i.imgur.com/TT6drhn.jpg"></div>
</div>
<div class="rest">
<h1>blah blah blah</h1>
</div>
</body>
</html>


推荐阅读