随着浏览器宽度/高度的变化,如何使用 CSS 动态调整图像大小? [英] How can I resize an image dynamically with CSS as the browser width/height changes?

查看:40
本文介绍了随着浏览器宽度/高度的变化,如何使用 CSS 动态调整图像大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何随着浏览器窗口调整图像大小,这里是我所做的到目前为止(或下载ZIP 格式的整个网站).

这在 Firefox 中工作正常,但在 Chrome 中存在问题:图像并不总是调整大小,它以某种方式取决于页面加载时窗口的大小.

这在 Safari 中也可以正常工作,但有时图像会以其最小宽度/高度加载.也许这是由图像大小引起的,我不确定.(如果加载正常,请尝试刷新几次以查看错误.)

关于如何使这个更防弹的任何想法?(如果需要 JavaScript,我也可以接受,但 CSS 更可取.)

解决方案

这个可以用纯 CSS 完成,甚至不需要媒体查询.

<块引用>

要使图像灵活,只需添加 max-width:100%height:auto.图片 max-width:100%height:auto 在 IE7 中有效,但在 IE8 中无效(是的,另一个奇怪的 IE 错误).要解决此问题,您需要为 IE8 添加 width:auto9.

来源:http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

CSS:

img {最大宽度:100%;高度:自动;宽度:自动9;/* ie8 */}

如果你想强制固定图像的最大宽度,只需将它放在一个容器中,例如:

<img src="...";/>

此处为 JSFiddle 示例.不需要 JavaScript.适用于最新版本的 Chrome、Firefox 和 IE(这是我测试过的所有版本).

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).

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.

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.)

解决方案

This can be done with pure CSS and does not even require media queries.

To make the images flexible, simply add max-width:100% and height:auto. Image max-width:100% and height:auto works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to add width:auto9 for IE8.

source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

CSS:

img {
    max-width: 100%;
    height: auto;
    width: auto9; /* 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 example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).

这篇关于随着浏览器宽度/高度的变化,如何使用 CSS 动态调整图像大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆