在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
当前回答
在多个皮肤或设计版本的情况下使用CSS背景图像。Javascript可以用来动态地改变一个元素的类,这将迫使它呈现不同的图像。如果使用IMG标签,可能会更加棘手。
其他回答
我想再补充两个论点:
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.
如果您将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来自动化该过程)。
另外,如果你不希望用户能够保存图像,背景图像也是有用的(尽管我从来没有需要这样做)。
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.
另一个背景-图像PRO: <ul>/<ol>列表的背景-图像。
如果背景图像是整体设计的一部分,并且在多个页面上重复使用,则使用背景图像。最好以背景精灵的形式进行优化。
对所有不属于整体设计的图像使用标签,并且很可能只放置一次,比如文章、人物的特定图像,以及值得添加到谷歌图像中的重要图像。
**我在<img>标签中唯一重复的图像是网站/公司标志。因为人们倾向于点击它进入主页,所以你用<a>标签来包装它。
一个小的输入, 我曾经遇到过响应式图像在iphone上的渲染速度减慢长达一分钟的问题,即使是小图像:
<!-- Was super slow -->
<div class="stuff">
<img src=".." width="100%" />
</div>
但是当切换到使用背景图像时,这个问题就消失了,这只有在针对较新的浏览器时才可行。