目前我使用的 img
除了 max-width
和 max-height
没有其他约束,我喜欢这样的事实,当我使用更大的图像我的浏览器会缩小图像以使其完全适合其区域(按钮、div 等),同时保持图像纵横比。
但是对于图像较小的情况,我希望浏览器在保持宽高比的同时放大图像(以便它占据整个宽度或高度)。
我试过使用 width:100%
或/和 height:100%
但这当然会拉伸(stretch)图像,这不是我想要的。
这是一个例子。
第一张图片很大,会适当缩小。
第二张图片很小而且没有放大……我不知道如何正确放大它。
这是我的问题!
我想要一个纯 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>
最佳答案
不需要做max-width
和 max-height
只需使用 width:100%;
反而。
如果您只定义宽度,图像将自动保持其纵横比。
这是一个 fiddle ,展示了它的实际效果: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%;
}
编辑
好的,在评论中反复讨论之后,我想我对您要寻找的内容有了更好的了解。而不是使用 <img>
按钮内的标签,我们可以只使用 CSS 应用 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;
所以这个解决方案并不完美,但如果您不关心对旧浏览器的支持,那么这应该可以满足您的需求。这是一个 fiddle :http://jsfiddle.net/68VRk/
关于HTML:如何使用 <img> 放大图像并保持纵横比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20694044/