在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?

这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。


当前回答

HTML用于内容,CSS用于设计。图像是必要的,它需要被屏幕阅读器拾取吗?如果答案是肯定的,那么就把图像放到HTML中。如果它纯粹是为了样式化,那么您可以使用CSS中的background-image属性来注入图像。正如这里很多人已经提到的,如果愿意,可以在图像上使用伪元素。

其他回答

浏览器并不总是默认设置为打印背景图像;如果你想让别人打印你的页面:)

一个小的输入, 我曾经遇到过响应式图像在iphone上的渲染速度减慢长达一分钟的问题,即使是小图像:

<!-- Was super slow -->
<div class="stuff">
    <img src=".." width="100%" />
</div>

但是当切换到使用背景图像时,这个问题就消失了,这只有在针对较新的浏览器时才可行。

One more benefit from using the <IMG> tag is related to SEO - i.e. you can provide additional information about the image in the ALT attribute of the image tag, while there's no way to provide such information when specifying the image through CSS and in that case only the image file name may be indexed by search engines. The ALT attribute definitely gives the <IMG> tag SEO advantage over the CSS approach. That's why according to me it is better to specify the images you want to rank well in the image search results (e.g. Google Image Search) using the <IMG> tag.

此外,我有一个画廊部分,有不一致的图片大小,所以即使这些图像显然被认为是内容,我使用背景图像和中心它们在divs设置大小。这类似于facebook在他们的相册里做的事情。

这里有一个技术上的考虑:图像是动态生成的吗?在HTML中生成<img>标记往往比尝试动态编辑CSS属性容易得多。