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

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


当前回答

还要注意,大多数搜索引擎蜘蛛不会索引CSS背景图像,因此背景图像将被忽略,你将无法从搜索引擎获得任何流量(简而言之,没有SEO好处)。

其中,所有用标签定义的图像都被索引(除非手动排除),并且如果它们的标题/alt属性和文件名经过适当优化(w.r.t一些关键字),就可以从搜索引擎带来流量。

其他回答

我想再补充两个论点:

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.

只是在工作中抛出一个扳手-我的意见是,你不应该使用img标签。HTML意味着内容,而不是视觉风格。你页面上的所有图像都应该来自CSS,让你的HTML代码纯粹。(即使它确实需要更长的时间来构建)

只是一个小的添加,你应该使用img标签,如果你想让用户能够“右键单击”和“save-image”/“save-picture”,所以如果你打算将图像作为资源提供给其他人。

使用背景图像将(据我所知在大多数浏览器上)禁用直接保存图像的选项。

如果您将CSS放在外部文件中,那么将站点中频繁使用的图像(例如头部图像)显示为背景图像通常是很方便的,因为这样您以后就可以灵活地更改图像。

例如,假设你有以下HTML:

<div id="headerImage"></div>

...和CSS:

#headerImage {
    width: 200px;
    height: 100px;
    background: url(Images/headerImage.png) no-repeat;
}

几天后,您更改了图像的位置。你所要做的就是更新CSS:

#headerImage {
    width: 200px;
    height: 100px;
    background: url(../resources/images/headerImage.png) no-repeat;
}

否则,您必须在每个HTML文件中更新适当的<img>标记的src属性(假设您没有使用服务器端脚本语言或CMS来自动化该过程)。

另外,如果你不希望用户能够保存图像,背景图像也是有用的(尽管我从来没有需要这样做)。

IMG首先加载,因为src是在html文件本身,而在背景图片的情况下,源是在样式表中提到的,所以图片在样式表加载后加载,延迟了网页的加载。