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

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


当前回答

有些答案把情况复杂化了。这是一个非常简单的情况。

每次你想放一张图片的时候就回答这个问题:

这是内容的一部分还是设计的一部分?

如果你不能回答这个问题,你可能不知道你在做什么或你想做什么!

此外,不要仅仅因为你想要“打印机友好型”而考虑这两种技术。也不要从SEO的角度用CSS隐藏内容。如果您发现自己在CSS文件中管理内容,那么您是在搬起石头砸自己的腿。这只是什么是内容或不内容的一个微不足道的决定。其他方面都应该被忽略。

其他回答

当我想让它们100%可拉伸时,我使用image而不是background-image,大多数浏览器都支持。

以上回答只考虑设计方面。我在搜索引擎优化方面列出了它。

何时使用<img />

When Your Image need to be indexed by search engine If it has relation to content, including cards (click areas), but not related to design. Design is probably the most difficult thing to parse here because so it's all design right. I would say perhaps functional design (Cards, thumbnails, profile images, things you can click) vs Aesthetic design which is mostly used for sites appeal. List item If your image is not too small ( not iconic images ). Images where you can add alt and title attribute. Images from a webpage which you want to print using print media css

何时使用CSS背景图像

纯粹用于设计的图像。 与内容无关。 小图像,我们可以玩CSS3。 重复图片(在博客作者图标中,每篇文章都会重复日期图标等)。

因为我将基于这些原因使用它们。这些都是图像搜索引擎优化的良好实践。

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

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

我想再补充两个论点:

An img tag is good if you need to resize the image. E.g. if the original image is 100px by 100 px, and you want it to be 80px by 80px, you can set the CSS width and height of the img tag. I don't know of any good way to do this using background-image. EDIT: This can now also be done with a background-image, using the background-size CSS3 attribute. Using background-image is good when you need to dynamically switch between sprites. E.g. if you have a button image, and you want a separate image displayed when the cursor is hovering over the element, you can use a background image containing both the normal and hover sprites, and dynamically change the background-position.