HTML:如何使用<img/>升级图像并保持纵横比?

时间:2013-12-20 00:03:23

标签: html css image

目前我正在使用img而没有max-widthmax-height之外的其他约束,我喜欢这样一个事实:当我使用更大的图像时,我的浏览器会缩小图像以完全适合它在保持图像宽高比的同时,在其区域(按钮,div,等等)。

但是对于图像较小的情况,我希望浏览器在保持宽高比的同时升级图像(使其占据整个宽度或高度)。

我尝试使用width:100%或/和height:100%进行游戏,但当然这会拉伸图像,这不是我想要的。

这是一个例子 第一张图片很大,会适当缩小尺寸 第二个图像很小,没有高档...我不知道如何正确升级它。 那是我的问题!
我想要一个纯CSS解决方案,如果可能的话没有javascript。

注意:我不知道图像的确切大小是什么,如果它太小而我想要缩小尺寸,如果它太小,我想缩小尺寸。

<!DOCTYPE html>
<html>
<body>
    <div>
        <button type="button" style="width:256px; height:256px">
            <img src="http://www.google.com/doodle4google/images/d4g_logo_global.jpg" alt="Smiley face" style="max-width:100%; max-height:100%">
        </button>

        <button type="button" style="width:256px; height:256px">
            <img src="http://static.autodesk.net/etc/designs/v2171/autodesk/adsk-design/images/autodesk_header_logo_140x23.png" style="max-width:100%; max-height:100%">
        </button>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

无需执行max-widthmax-height只需使用width:100%;即可。

如果只定义宽度,图像将自动保持其宽高比。

这是一个小提琴,展示了它的实际效果:http://jsfiddle.net/Ea26r/

HTML:

<div>
    <button type="button">
        <img src="..." alt="Smiley face">
    </button>
    <button type="button">
        <img src="..." >
    </button>
</div>

CSS:

img {
    width: 100%;
}

修改

好的,所以在评论中来回反复思考后,我想我会更好地掌握你所寻找的东西。我们可以使用CSS将<img>应用于按钮,然后使用background-image缩放照片,而不管其方向如何,而不是在按钮内使用background-size: contain;标记。像这样:

HTML

<button id="button1" type="button" style="width:256px; height:32px">
</button>

CSS

#button1 {
    background-image: url('http://www.url-to-image-here.com');
    background-size: contain;
    background-repeat: no-repeat;
}

现在,请记住,IE8及以下版本不支持background-size:contain;,因此这个解决方案并不完美,但如果您不关心对旧浏览器的支持,那么这应该可以满足您的需求。这是一个小提琴:http://jsfiddle.net/68VRk/