Html 如何使用 CSS 将图像调整为屏幕高度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7367468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:32:44  来源:igfitidea点击:

How to make an image resize to the screens height with CSS?

htmlcssimageresize

提问by Mohammad

Unlike many people who want an image to fill out the whole screen, I only care about the image height. How can I use CSS (preferably not JavasScript) to make an image with any size, fill up to 100% of the maximum possible browser window heightwhile keeping aspect ratio of the image, the re-sized width of the image in respect to the browser does not matter.

不像很多人想要一张图片填满整个屏幕,我只关心图片的高度。我如何使用 CSS(最好不是 JavasScript)制作任何尺寸的图像,填充最多 100% 的最大可能浏览器窗口高度,同时保持图像的纵横比,重新调整图像的宽度相对于浏览器无所谓。

I'm working with this html:

我正在使用这个 html:

<div class="images">
  <img/>
</div>

Thank you so much!

非常感谢!

回答by Joseph Marikle

img { height:100% }

or if you want to be explicit

或者如果你想明确

img { height:100%; width:auto; }

height 100%: http://jsfiddle.net/jmarikle/vz7q2bnk/
width 100%: http://jsfiddle.net/jmarikle/vz7q2bnk/1/

高度 100%:http: //jsfiddle.net/jmarikle/vz7q2bnk/
宽度 100%:http: //jsfiddle.net/jmarikle/vz7q2bnk/1/

EDIT:

编辑:

This answer needed some attention. The demo was broken and generally a mess. I've updated it with new images, updated rule to compensate for the inline nature of images, and normalized height and width of the body and html elements.

这个答案需要一些注意。演示被破坏了,通常是一团糟。我已经用新图像更新了它,更新了规则以补偿图像的内联性质,以及规范化的 body 和 html 元素的高度和宽度。

回答by Joe

This might be overkill:

这可能有点矫枉过正:

.img {
    position: absolute;
    height: 100%;
    top: 0;
    bottom: 0;
}

回答by Sam Dutton

You might also want to take a look at the vh, vw, vmin and vmax CSS units – which are pretty well supported. There's a good article describing how to achieve 100% height here.

您可能还想看看 vh、vw、vmin 和 vmax CSS 单元——它们得到了很好的支持。有一篇很好的文章描述了如何在此处实现 100% 高度。

BTW – beware of whitespace: this can add an unwanted margin. Removing the space, adding a float, or using the font-size: 0hack will sort this out. Also, when using other methods, remember to set height: 100%for the body and html elements.

顺便说一句 - 当心空格:这会增加不需要的边距。删除空格、添加浮点数或使用font-size: 0hack 将解决此问题。另外,在使用其他方法时,记得height: 100%为 body 和 html 元素设置。