在HTML与CSS中指定图像尺寸以进行页面加载

在HTML与CSS中指定图像尺寸以进行页面加载

本文介绍了在HTML与CSS中指定图像尺寸以进行页面加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很久以前从某个地方学到了在HTML文档中指定< img> 元素的宽度和高度可以加快并改善页面加载体验,并且一般都遵守这种做法:

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" />

我现在面临的情况是我在一个页面上有大量图像,我更喜欢通过CSS设置尺寸,以便更容易控制和更少重复的HTML代码:

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;}

虽然这不是一个非常严重的问题,但我想知道是否宣布CSS中的维度与在HTML中声明维度具有相同的好处,或者它是否应该直接在HTML中完成?

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?

欢迎任何见解。

谢谢

推荐答案

我想如果样式表立即可用,图像尺寸将立即应用于布局,这是练习的重点。

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

当浏览器布局页面时,它需要能够在可替换元素(如图像)周围流动。它甚至可以在下载图像之前开始呈现页面,前提是它知道包装不可替换元素的尺寸。如果在包含文档中未指定维度,或者指定的维度与实际图像的维度不匹配,则浏览器将需要重排并在下载图像后重新绘制。要防止回流,请在HTML < img> 标记,或CSS 中指定所有图像的宽度和高度。

When the browser lays out the page, it needs to be able to flow around replaceable elements such as images. It can begin to render a page even before images are downloaded, provided that it knows the dimensions to wrap non-replaceable elements around. If no dimensions are specified in the containing document, or if the dimensions specified don't match those of the actual images, the browser will require a reflow and repaint once the images are downloaded. To prevent reflows, specify the width and height of all images, either in the HTML <img> tag, or in CSS.

这篇关于在HTML与CSS中指定图像尺寸以进行页面加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 22:23