在保持纵横比的同时,使溢出隐藏div内的img标签宽度和高度100%

Jim*_*Jim 2 html css css3

我需要在溢出隐藏div内部使img标签宽度和高度100%,同时保持纵横比.

我达到的目的是将图像放在溢出隐藏的div中,图像的最大宽度为100%,自动高度.

<div id="foo">
    <img src="http://www.engineering.com/Portals/0/BlogFiles/swertel/heart-cloud.jpg" />
</div>
Run Code Online (Sandbox Code Playgroud)

但我面临的问题不是高度100%

在此输入图像描述

查看代码中的代码http://fiddle.jshell.net/TARwL/

并仔细看看div#cover是100%宽度和高度是完美的外观,我想看到我的代码做同样的事情

我不能使用background-size:cover方法,因为旁边不能在旧浏览器中工作,我无法点击右键并保存图像,这对我很重要

Jim*_*Jim 6

I rethought and I found eligible solution for me, I don't know if will suit anyone else !!

The Image will be background size cover and at the same time I will add the image inside the same div with 100% width and height and 0 opacity

So the image will show like cover and anyone can click on the same area and use the image like normal (copy link, download, etc.)

HTML

<div style="background-image:url(http://www.engineering.com/Portals/0/BlogFiles/swertel/heart-cloud.jpg)">
    <img src="http://www.engineering.com/Portals/0/BlogFiles/swertel/heart-cloud.jpg" />
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

 div{
        width: 300px;
        height: 300px;
        display:inline-block;
        vertical-align: top;
        background-size:cover;
        background-position:50% 50%;
    }

    div img{
        width: 100%;
        height: 100%;
        opacity: 0;
        /* OLD IE */
        zoom: 1;
        filter: alpha(opacity=0);
    }
Run Code Online (Sandbox Code Playgroud)

Code In Action http://jsfiddle.net/Jim_Toth/mVtJc/1/

  • 我实际上更喜欢你的回答.非常好. (2认同)