在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
在什么情况下使用HTML IMG标记来显示图像更合适,而不是CSS背景图像,反之亦然?
这些因素可能包括可访问性、浏览器支持、动态内容或任何类型的技术限制或可用性原则。
当前回答
使用背景图像时,您需要明确指定尺寸。如果你事先不知道它们或无法确定它们,这可能是一个严重的问题。
<img />的一个大问题是覆盖。如果我想在我的图像上添加一个CSS内阴影(box-shadow:inset 0 0 5px rgb(0,0,0,.5))怎么办?在本例中,由于<img />不能有子元素,因此需要使用定位并添加等同于无用标记的空元素。
总之,这是一种情境。
其他回答
我很惊讶没有人提到这个: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转换的信息。
IMG首先加载,因为src是在html文件本身,而在背景图片的情况下,源是在样式表中提到的,所以图片在样式表加载后加载,延迟了网页的加载。
我想再补充两个论点:
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。
Background = CSS背景。
当我想让它们100%可拉伸时,我使用image而不是background-image,大多数浏览器都支持。