When to use IMG vs. CSS background
In what situations is it more appropriate to use an HTML IMG
tag to display an image, as opposed to a CSS background-image
, and vice-versa?
Factors may include accessibility, browser support, dynamic content, or any kind of technical limits or usability principles.
Proper uses of IMG
IMG
if you intend to have people print your page and you want the image to be included by default. —JayTee IMG
(with alt
text) when the image has an important semantic meaning, such as a warning icon. This ensures that the meaning of the image can be communicated in all user-agents, including screen readers. Pragmatic uses of IMG
IMG
plus alt attribute if the image is part of the content such as a logo or diagram or person (real person, not stock photo people). —sanchothefat IMG
if you rely on browser scaling to render an image in proportion to text size. IMG
for multiple overlay images in IE6. IMG
with a z-index
in order to stretch a background image to fill its entire window. Note, this is no longer true with CSS3 background-size; see #6 below.
img
instead of background-image
can dramatically improve performance of animations over a background. When to use CSS background-image
background-image
if you intend to have people print your page and you do not want the image to be included by default. —JayTee background-image
if you need to improve download times, as with CSS sprites. background-image
if you need for only a portion of the image to be visible, as with CSS sprites. background-image
with background-size:cover
in order to stretch a background image to fill its entire window. It's a black and white decision to me. If the image is part of the content such as a logo or diagram or person (real person, not stock photo people) then use the <img />
tag plus alt attribute. For everything else there's CSS background images.
The other time to use CSS background images is when doing image-replacement of text eg. paragraphs/headers.
I'm surprised no one's mentioned this yet: CSS transitions .
You can natively transition a div
's background image:
#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);
}
This saves any kind of JavaScript or jQuery animation to fade an <img/>
's src
.
More information about transitions on MDN.
链接地址: http://www.djcxy.com/p/4818.html上一篇: 图像和CSS3渐变相同的元素?
下一篇: 何时使用IMG与CSS背景