如何让图像适应大小以匹配其容器的高度

How to get an image to adapt in size to match the HEIGHT of its container

我正在尝试在 CSS 中执行此操作并认为这很简单,我以前从未真正需要这样做,但现在我已经尝试过但无法正常工作.

我有一个容器,里面有一张图片。 我想要的是根据高度而不是宽度来增加图像的大小。我认为这会像这样简单:

#project-header {
   height: 50%;
}
#project-header img {
display: block;
height: 100%;
width: auto;
margin: auto;
}

这不起作用。

我的容器是浏览器高度的 50% window,所以这一切都很好,但图像以其原始大小显示。

我希望它在使用 width: 100%, height: auto; 时表现得像响应式图像一样;但我的图像始终是其原始大小(因此从容器中流出)并且不适应其容器的高度。

我错过了什么吗?或者这是不可能的?有办法吗?

要让您的 div 获得 height: 50%,您首先需要将 height:100% 给予所有父 div 一直到 html标签

html, body{
height:100%;
}

然后你的 css 将按预期工作

    #project-header{
            height:50%;
    }
    #project-header img{
            max-height: 100%;
            width: auto;
    }

html, body{
  height:100%;
  /* width: 95%; */
}

#project-header{
  height:50%;
  width: 500px;
}
#project-header img{
  max-height: 100%;
  width: auto;
}

.second-image{
  height:50%;
  /* width: 500px; */
}
.second-image img {
    max-width: 100vw;
    height:auto;
    width:auto;
    max-height:100vh;
}
Method 1
    <div id="project-header">
      <img src="http://via.placeholder.com/350x150" alt="">
    </div>
    
    
    Method 2
    <div class="second-image">
      <img src="http://via.placeholder.com/350x150" alt="">
    </div>