在 HTML 与 CSS 中指定页面加载的图像尺寸
我很久以前就从某个地方了解到,在 HTML 文档中指定 元素的宽度和高度可以加快并改善页面加载体验,并且通常坚持这种做法
<img src="" width="100" height="100" />
:现在面临的情况是,我在单个页面上有大量图像,并且我更喜欢通过 CSS 设置尺寸,以便更轻松地控制和减少重复的 HTML 代码:
.whatever img {width: 100px; height: 100px;}
尽管这并不是一个非常严重的问题问题,我想知道在 CSS 中声明尺寸是否与在 HTML 中声明尺寸具有相同的好处,或者是否应该直接在 HTML 中完成?
任何见解都会受到欢迎。
谢谢
I've learnt from somewhere a long time ago that specifying width and height for <img>
elements in an HTML document speeds up and improves the page loading experience, and have generally kept to this practice:
<img src="" width="100" height="100" />
I'm now faced with a situation where I have a very large number of images on a single page, and I'd prefer to set the dimensions via CSS for both easier control and less repetitive HTML code:
.whatever img {width: 100px; height: 100px;}
Although this isn't a hugely serious issue, I'm wondering whether declaring the dimensions in CSS will have the same benefits as declaring the dimensions in HTML, or whether it ought to just be done in HTML directly?
Any insight would be welcome.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想如果样式表立即可用,图像尺寸将立即应用于布局,这就是练习的重点。
Google 的 pagespeed 规则支持这一猜测。他们似乎很擅长以这种方式指定图像(强调我的):
I guess if the style sheet is available immediately, the image dimensions will immediately apply to the layout, which is the whole point of the exercise.
That guess is supported by Google's pagespeed rules. They seem to be fine with specifying images that way (emphasis mine):
在属性中定义宽度和高度(与在 CSS 中相对)的关键区别在于,它会变成数据,而不是表示参数。想象一下管理以下样式表
这不必要地将 CSS 与图像纠缠在一起。它还限制了自适应布局,即当推断出图像尺寸之一时(例如
width: 100%
),您不能再让尚未加载的图像占用正确的空间。另外,请考虑 CSS 规则,例如
object-fit< /代码>
。可能会出现关于
width
和heigth
样式属性含义的混淆。The crucial difference between defining width and height in an attribute (as opposed to in CSS) is that it then becomes data, not a presentation parameter. Just imagine managing a following stylesheet
This needlessly entangles CSS with images. It also restricts adaptive layout, i.e. you can no longer have not-yet-loaded images take up correct space when one of their dimensions is inferred (e.g.
width: 100%
).Also, consider CSS rules such as
object-fit
. Confusion about whatwidth
andheigth
style properties then mean may arise.