当浏览器宽度/高度变化时,如何使用CSS动态调整图片大小? [英] How can I resize an image dynamically with CSS as the browser width/height changes?
问题描述
我想知道如何在浏览器视窗中调整图片大小,这里是我所做的(或下载整个网站的ZIP )。
I wonder how I could make an image resize along with the browser window, here is what I have done so far (or download the whole site in a ZIP).
此作品可以在Firefox中,但它在Chrome中有问题:图片不总是调整大小,它在某种程度上取决于页面加载时的窗口大小。
This works okay in Firefox, but it has problems in Chrome: the image does not always resize, it somehow depends on the size of the window when the page was loaded.
在Safari中工作正常,但有时图像加载其最小宽度/高度。也许这是由图像大小造成的,我不知道。 (如果它载入正常,请尝试刷新几次以查看错误。)
This also works okay in Safari, but sometimes the image is loaded with its minimum width/height. Maybe this is caused by the image size, I am not sure. (If it loads okay, try to refresh several times to see the bug.)
有关如何使这个更加防弹的任何想法? (
Any ideas on how could I make this more bulletproof? (If JavaScript will be needed I can live with that, too, but CSS is preferable.)
推荐答案
此可以可以使用纯CSS,甚至不需要媒体查询。
This can be done with pure CSS and does not even require media queries.
$ c> max-width:100%和
height:auto
。图片max-width:100%
和height:auto
在IE7中有效,但不是在IE8中IE错误)。要解决这个问题,您需要为IE8添加width:auto\9
。
To make the images flexible, simply add
max-width:100%
andheight:auto
. Imagemax-width:100%
andheight:auto
works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to addwidth:auto\9
for IE8.
来源: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries
CSS:
img {
max-width: 100%;
height: auto;
width: auto\9; /* ie8 */
}
如果要强制执行固定的最大宽度图像,只需将其放在容器中即可:
And if you want to enforce a fixed max width of the image, just place it inside a container, for example:
<div style="max-width:500px;">
<img src="..." />
</div>
JSFiddle示例。无需JavaScript。适用于最新版本的Chrome,Firefox和IE(这是我测试过的)。
JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).
这篇关于当浏览器宽度/高度变化时,如何使用CSS动态调整图片大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!