gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:58:33 26 4
gpt4 key购买 nike

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

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

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

这不起作用。

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

我希望它在使用 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>

关于css - 如何让图像适应大小以匹配其容器的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49479177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com