在哪里指定图像尺寸以实现最快渲染:在 HTML 中还是在 CSS 中?
我了解到明确指定图像尺寸是最佳实践。然后,浏览器可以在仍然下载图像本身的同时布局页面,从而缩短(感知的)页面渲染时间。
这是真的吗?如果是这样,在 HTML 或 CSS 中指定尺寸是否有区别?
- HTML:
- 内联 CSS:
- 外部 CSS:
#myImage { width: 200px;高度:200px; }
I've learned that it is a best practice to explicitly specify image dimensions. The browser can then already layout the page while still downloading the images themselves, thereby improving (percieved) page rendering time.
Is this true? And if so, is there a difference in specifying the dimensions in either HTML or CSS?
- HTML:
<img src="" width="200" height="100">
- Inline CSS:
<img src="" style="width: 200px; height: 100px">
- External CSS:
#myImage { width: 200px; height: 200px; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据 Google Page Speed,这并不重要如果您通过 CSS 或 HTML 指定尺寸,只要您的 CSS 面向 IMG 标签本身而不是父元素:
但是,请注意,他们建议不要使用这些尺寸调整图像大小,即始终使用实际尺寸:
According to Google Page Speed, it does not really matter if you specify the dimensions via CSS or HTML, as long as your CSS targets the IMG tag itself and not a parent element :
However, note that they advise not to resize the image using these dimensions, ie to always use the real dimensions :
我倾向于在 CSS 中做到这一点。当有多个具有相同尺寸的图像时,这当然是一个胜利(因此您可以执行诸如
.comment img.usergroup { width: 16px; height: 16px; }
之类的操作),并且具有相同的图像可以在不同的样式表中进行缩放,例如用户可选择的主题。当您拥有仅在网站上使用一次的完全独立的图像时,将它们的大小抽象为 CSS 并没有真正意义,因此 HTML 版本可能更合适。
I tend to do it in the CSS. This is certainly a win when there are multiple images with the same dimensions (so you can do stuff like
.comment img.usergroup { width: 16px; height: 16px; }
), and have the same images subject to scaling in different stylesheets like user-selectable themes.When you have completely independent images that are used on the site only once, it doesn't really make sense to abstract their size out to CSS, so the HTML version would probably be more appropriate there.
我认为 CSS 为您提供了更大的灵活性:您可以专门设置宽度或高度,同时将其他尺寸设置为
auto
。但是当设置两个尺寸时,我不认为有什么区别。I think CSS gives you more flexibility: you can specifically set the width or height while setting the other dimension to
auto
. But when setting both dimensions, I don't thing there's a difference.这并不能直接回答您的问题,但我不会依赖图像的尺寸来进行页面布局。相反,将图像包含在块级元素中。这使得 HTML 和 CSS 不必保存它们实际上不应该保存的信息,因为图像可能会不时发生变化。
This does not answer your question directly, but I would not rely on the dimensions of your image for page layout. Instead include the image in a block level element. This relieves both the HTML and CSS from having to hold information that it really shouldn't as the image may change from time to time.
如果您将大图像放入没有尺寸的 HTML 页面中,您一定会注意到下载图像时页面布局发生变化(通过互联网连接,如果不是本地下载)。
根据其他答案,无论是在 HTML 还是 CSS 中执行此操作都没有太大区别。
If you put a large image in an HTML page without dimensions, you should definitely notice the page layout shifting as the image is downloaded (over an internet connection, if not locally).
As per other answers, it doesn’t make much difference whether you do this in the HTML or the CSS.