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

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


当前回答

还有一个原因!如果你有一个响应式的设计,并且想通过媒体查询来划分低分辨率、中分辨率和高分辨率图像的使用,那么你也应该使用背景。

其他回答

在多个皮肤或设计版本的情况下使用CSS背景图像。Javascript可以用来动态地改变一个元素的类,这将迫使它呈现不同的图像。如果使用IMG标签,可能会更加棘手。

Img是一个HTML标记是有原因的,因此应该使用它。用于引用或说明事物,如在文章中。

此外,如果图像有意义或必须是可点击的,img比css背景更好。对于所有其他情况,我认为,css背景可以使用。

尽管这是一个需要反复讨论的话题。

来自法国巴黎的学生

正确使用IMG

如果您打算使用IMG 人们打印您的页面,您希望在默认情况下包含图像。 -JayTee 当图像具有重要的语义含义时,例如警告图标,使用IMG(带有alt文本)。这确保了图像的含义可以在所有用户代理(包括屏幕阅读器)中传达。

IMG的实用用途

Use IMG plus alt attribute if the image is part of the content such as a logo or diagram or person (real person, not stock photo people). —sanchothefat Use IMG if you rely on browser scaling to render an image in proportion to text size. Use IMG for multiple overlay images in IE6. Use IMG with a z-index in order to stretch a background image to fill its entire window.Note, this is no longer true with CSS3 background-size; see #6 below. Using img instead of background-image can dramatically improve performance of animations over a background.

何时使用CSS背景图像

Use CSS background images if the image is not part of the content. —sanchothefat Use CSS background images when doing image-replacement of text eg. paragraphs/headers. —sanchothefat Use background-image if you intend to have people print your page and you do not want the image to be included by default. —JayTee Use background-image if you need to improve download times, as with CSS sprites. Use background-image if you need for only a portion of the image to be visible, as with CSS sprites. Use background-image with background-size:cover in order to stretch a background image to fill its entire window.

对我来说,这是个非黑即白的决定。如果图像是内容的一部分,如logo、图表或人物(真实人物,而不是库存照片人物),则使用<img />标记加上alt属性。其他的都有CSS背景图片。

另一个使用CSS背景图像的时间是在做文本的图像替换时。段落/头。

我很惊讶没有人提到这个:CSS过渡。

你可以本地转换一个div的背景图像:

#some_div {
    background-image:url(image_1.jpg);
    -webkit-transition:background-image 0.5s;
    /* Other vendor-prefixed transition properties */
    transition:background-image 0.5s;
}

#some_div:hover {
    background-image:url(image_2.jpg);
}

这将保存任何类型的JavaScript或jQuery动画来淡化<img/>的src。

更多关于MDN转换的信息。