Image in full screen with img tag

做~自己de王妃 提交于 2019-11-28 20:33:30

问题


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

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: cover but with the image tag.

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.


回答1:


There are several ways to make an image cover a div with the image tag, the simplest is to use the object-fit property like this :

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 :

  • vertical and horizontal centering with absolute positioning, negative top, bottom, left and right values combined with margin:auto;
  • image always covers viewport with 100% min-height and 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="">


来源:https://stackoverflow.com/questions/24650218/image-in-full-screen-with-img-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!