如何使图像占据剩余高度,并确定宽度

时间:2017-07-24 18:42:13

标签: html css

考虑this question及其选定的答案。

我在下面的代码中使用了所选答案的代码,将#div1更改为.header,将#div2更改为.contents并将两个div放在容器中。

我需要的是:在.contents div中应该放置一个图像。此图像应与.contents div的高度相同(因此占用容器中的剩余高度)。图像的宽度应为自动,以保持纵横比。

现在的问题是:我如何管理所有div与图像的计算宽度具有相同的宽度?

以下代码执行上述所有操作,但div与图像的宽度不同。

    .container {
      position: absolute;
      height: 60%; /* this is a requirement, height should be a percentage */
      width: 40%;  /* this line should be removed, width should be width of the image */
      border: 5px solid black;	  
    }
    .header {
	  width: 100%; /* width should be width of the image */
      height: 100px; 
      background: red;
    }
    .contents {
      width: 100%; /* width should be width of the image */
      position: absolute;
      top: 100px;
      bottom: 0;
      background: blue;
    }
    .contents img {
      height: 100%;
      width: auto; /* width should be computed considering height and keeping aspect ratio */
    }	
 <div class="container">
      <div class="header"></div>
      <div class="contents">
        <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" title="" />
      </div>
    </div>

如果可能,我更喜欢没有javascript的解决方案。

1 个答案:

答案 0 :(得分:0)

        
 html, body, .shell {
      height: 100%; // every parent element needs specified height
}

    .container {
  display: inline-block;
      height: 60%; /* this is a requirement, height should be a percentage */
      //width: 40%;  /* this line should be removed, width should be width of the image */
      border: 5px solid black;	  
    }
    .header {
	  width: 100%; /* width should be width of the image */
      height: 100px; 
      background: red;
    }
    .contents {
      height: calc(100% - 100px);
      top: 100px;
      bottom: 0;
      background: blue;
    }
    .contents img {
      height: 100%;
      width: auto; /* width should be computed considering height and keeping aspect ratio */
    }
 <div class="shell">
   <div class="container">
        <div class="header"></div>
        <div class="contents">
        <img src="http://via.placeholder.com/200x200" width="200" height="200" alt="" title="" />
      </div>
   </div>
 </div>