在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
当前回答
在多个皮肤或设计版本的情况下使用CSS背景图像。Javascript可以用来动态地改变一个元素的类,这将迫使它呈现不同的图像。如果使用IMG标签,可能会更加棘手。
其他回答
有些答案把情况复杂化了。这是一个非常简单的情况。
每次你想放一张图片的时候就回答这个问题:
这是内容的一部分还是设计的一部分?
如果你不能回答这个问题,你可能不知道你在做什么或你想做什么!
此外,不要仅仅因为你想要“打印机友好型”而考虑这两种技术。也不要从SEO的角度用CSS隐藏内容。如果您发现自己在CSS文件中管理内容,那么您是在搬起石头砸自己的腿。这只是什么是内容或不内容的一个微不足道的决定。其他方面都应该被忽略。
前景= img。
Background = 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转换的信息。
在多个皮肤或设计版本的情况下使用CSS背景图像。Javascript可以用来动态地改变一个元素的类,这将迫使它呈现不同的图像。如果使用IMG标签,可能会更加棘手。
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.