在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
当前回答
我想再补充两个论点:
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.
其他回答
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背景图像。
此外,我有一个画廊部分,有不一致的图片大小,所以即使这些图像显然被认为是内容,我使用背景图像和中心它们在divs设置大小。这类似于facebook在他们的相册里做的事情。
使用背景图像时,您需要明确指定尺寸。如果你事先不知道它们或无法确定它们,这可能是一个严重的问题。
<img />的一个大问题是覆盖。如果我想在我的图像上添加一个CSS内阴影(box-shadow:inset 0 0 5px rgb(0,0,0,.5))怎么办?在本例中,由于<img />不能有子元素,因此需要使用定位并添加等同于无用标记的空元素。
总之,这是一种情境。
以上回答只考虑设计方面。我在搜索引擎优化方面列出了它。
何时使用<img />
When Your Image need to be indexed by search engine If it has relation to content, including cards (click areas), but not related to design. Design is probably the most difficult thing to parse here because so it's all design right. I would say perhaps functional design (Cards, thumbnails, profile images, things you can click) vs Aesthetic design which is mostly used for sites appeal. List item If your image is not too small ( not iconic images ). Images where you can add alt and title attribute. Images from a webpage which you want to print using print media css
何时使用CSS背景图像
纯粹用于设计的图像。 与内容无关。 小图像,我们可以玩CSS3。 重复图片(在博客作者图标中,每篇文章都会重复日期图标等)。
因为我将基于这些原因使用它们。这些都是图像搜索引擎优化的良好实践。