在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
当前回答
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.
其他回答
在多个皮肤或设计版本的情况下使用CSS背景图像。Javascript可以用来动态地改变一个元素的类,这将迫使它呈现不同的图像。如果使用IMG标签,可能会更加棘手。
一些应该使用background-image的其他场景:
当鼠标悬停在图像上时,希望图像发生变化。 当您想要添加圆角的图像。如果使用img,图像会从圆角中泄漏出来。
HTML用于内容,CSS用于设计。图像是必要的,它需要被屏幕阅读器拾取吗?如果答案是肯定的,那么就把图像放到HTML中。如果它纯粹是为了样式化,那么您可以使用CSS中的background-image属性来注入图像。正如这里很多人已经提到的,如果愿意,可以在图像上使用伪元素。
这里有一个技术上的考虑:图像是动态生成的吗?在HTML中生成<img>标记往往比尝试动态编辑CSS属性容易得多。
IMG首先加载,因为src是在html文件本身,而在背景图片的情况下,源是在样式表中提到的,所以图片在样式表加载后加载,延迟了网页的加载。