在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
当前回答
在多个皮肤或设计版本的情况下使用CSS背景图像。Javascript可以用来动态地改变一个元素的类,这将迫使它呈现不同的图像。如果使用IMG标签,可能会更加棘手。
其他回答
一些应该使用background-image的其他场景:
当鼠标悬停在图像上时,希望图像发生变化。 当您想要添加圆角的图像。如果使用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.
使用背景图像时,您需要明确指定尺寸。如果你事先不知道它们或无法确定它们,这可能是一个严重的问题。
<img />的一个大问题是覆盖。如果我想在我的图像上添加一个CSS内阴影(box-shadow:inset 0 0 5px rgb(0,0,0,.5))怎么办?在本例中,由于<img />不能有子元素,因此需要使用定位并添加等同于无用标记的空元素。
总之,这是一种情境。
关于使用CSS TranslateX/Y(正确的html动画方式)动画图像-如果你做一个Chrome时间轴记录的CSS背景图像被动画和IMG标签被动画,你会发现绘制时间大大缩短了CSS背景图像。
只是在工作中抛出一个扳手-我的意见是,你不应该使用img标签。HTML意味着内容,而不是视觉风格。你页面上的所有图像都应该来自CSS,让你的HTML代码纯粹。(即使它确实需要更长的时间来构建)