Html 带有 img 标签的全屏图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24650218/
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 02:13:09  来源:igfitidea点击:

Image in full screen with img tag

htmlcssimageresponsive-designbackground-image

提问by Anju Aravind

I am using the img tag for my slider images, I need the image to be full width and height and centeredinside its' container.

我正在为我的滑块图像使用 img 标签,我需要图像为全宽和全高,并在其容器内居中

My problem is when I resize the window width, my image becomes small and it's height doesn't follow the window height. I need the same behaviour as background-size: coverbut with the image tag.

我的问题是当我调整窗口宽度时,我的图像变小并且它的高度不跟随窗口高度。我需要与图像标签相同的行为background-size: cover

background: url(../images/slider/002.jpg) center center; 
background-size: cover;

If I make the image as background, everything works fine, but the slider will not. I need to use the <img>tag. Here is my example.

如果我将图像作为背景,一切正常,但滑块不会。我需要使用<img>标签。这是我的例子

回答by web-tiki

There are several ways to make an image cover a divwith the image tag, the simplest is to use the object-fit propertylike this :

有几种方法可以使图像覆盖带有图像标签的 div,最简单的方法是使用object-fit 属性,如下所示:

html,body{
    margin:0;
    height:100%;
}
img{
  display:block;
  width:100%; height:100%;
  object-fit: cover;
}
<img src="http://i.imgur.com/5NK0H1e.jpg" alt="">

The browser support is good for object-fit (see canIuse) but if you need to support more browsers (like IE), you can use this technique to center a image fullscreen image with the <img>tag:

浏览器支持有利于对象匹配(请参阅canIuse),但如果您需要支持更多浏览器(如 IE),您可以使用此技术将图像全屏图像与<img>标签居中

  • vertical and horizontal centering with absolute positioning, negative top, bottom, left and right values combined with margin:auto;
  • image always covers viewportwith 100% min-heightand min-width
  • 垂直和水平居中,绝对定位,负顶、底、左和右值结合 margin:auto;
  • 图像始终以 100%覆盖视口min-height并且min-width

DEMO :

演示:

html,body{
    margin:0;
    height:100%;
    overflow:hidden;
}
img{
    min-height:100%;
    min-width:100%;
    height:auto;
    width:auto;
    position:absolute;
    top:-100%; bottom:-100%;
    left:-100%; right:-100%;
    margin:auto;
}
<img src="http://i.imgur.com/5NK0H1e.jpg" alt="">