Is it better to define images in direct html or css? - html

If I have the choice to insert images directly into the html or in the css, say for example a link wrapped in an image I could do either...
<img src="#" alt="" width="" height="" />
Or I could do...
<a id="img" href="#"></a>
#img {background: url('#') no-repeat; height: #; width: #;}
Which is better and why? Both work as wanted but is there any difference to load times etc, or any considered better practice?

Using images in HTML is better when the image has any contextual meaning... if it is a decorative picture without any contextual meaning, then use CSS. CSS is for presentation, HTML is for content.
The best hint for you to determine whether to use HTML or CSS for a picture is:
If I remove the picture, will the web-page content still make sense?
An image in HTML is meant to provide a visual meaning in context, with a meaningful text fall-back. Using an A element without any content should be avoided since its content will have a relationship with the link, for browsers and web-crawlers (such a Google bot).
Use CSS images only for decorative purposes. Otherwise it can damage your search engine rankings. Always provide an alt attribute for images, determine what will it be imagining that an eventual visitor cannot see any images.

If the image has context, such as a logo, or a photo, I would suggest loading it as an <img> Make sure you are providing alt text for accessibility and SEO reasons as well.
If an image has no context in the scope of the page, then I think the correct place for it, is defined the in the CSS which controls the design.
The whole idea is to separate your presentation from your content as much as you can. An Image can be content, and if so, should be in it.

Generally, I try to put as many images in CSS as possible but Doozer and Mario have good points. If the image is important to the context, it can go in the HTML. I will also use <img> tags when text needs to float around and image.
One thing that CSS can do that <img> can't are CSS image sprites. This is the only real performance benefit that you'll get from one or the other. Performance-hungry websites like youtube.com will combine many images into one large composite image in order to cut down on the HTTP traffic (and therefore the page load times). For example, this is a sprite taken from youtube.com.

Follow principles of semantic HTML. If the image is content, ie a thumbnail, photo, or button, use an <img> element. If it is more a part of the page design, a background image may be more appropriate.
A more specific example: If you are using your image as an icon next to a text link, use a background-image:
<span class="printIcon" onclick="window.print()">Print</a>
.printIcon { background: url(...) no-repeat; padding-left: 20px }
If your image is the button itself, with no text aspect, use an <img> element with an appropriate alt attribute that would work to substitue for the image if it is unavailable.
<img src="printButton.png" alt="Print" onclick="window.print()" />

Related

Blank .gif with background image to display icons – semantic meaning?

In this article, an interesting technique to embed icons is presented:
<img src="blank.gif" class="chromium">
.chromium {
background:url(//ssl.google.com/imagepath.png) no-repeat;
width:250px;
height:250px;
}
The above 'Google' technique I like to explain to others as a transparent window image with a background image, essentially you're looking through a transparent image to see a background image.
Essentially, a transparent .gif is embedded as inline image. Using a class on the image tag, a background image & dimensions are applied
Now my question is: Why would anyone do something like that?
To my understanding, this implies the semantic meaning of an inline image, but still enables the use of sprites to display icons.
So maybe it could be useful to mark up something like this, where icons are used that are still related to the content, often in more abstract ways:
Still I really don't get it – is there any semantic advantage over using background images for icons without the transparent .gif?
Note that the image tag is missing the alt attribute, but I didn't want to change the quoted code snippet.
No, there is no semantic advantage, that I can see.
The img doesn't have an id to make it unique, nor an alt to describe the content. And the content doesn't convey any meaning whatsoever.
If he had included an alt or an id, then maybe there was something to say for this technique. But even then, it would still have the disadvantage of wasting bandwidth, having to load two image files instead of one.

How to define alternate text for link button? [duplicate]

This is one I have not had to tackle before. I need to use alt tags on all images in a site including those used by CSS background-image attribute.
There is no CSS property like this as far as I know, so what is the best way to do this please?
Background images sure can present data! In fact, this is often recommended where presenting visual icons is more compact and user-friendly than an equivalent list of text blurbs. Any use of image sprites can benefit from this approach.
It is quite common for hotel listings icons to display amenities. Imagine a page which listed 50 hotel and each hotel had 10 amenities. A CSS Sprite would be perfect for this sort of thing -- better user experience because it's faster. But how do you implement ALT tags for these images? Example site.
The answer is that they don't use alt text at all, but instead use the title attribute on the containing div.
HTML
<div class="hotwire-fitness" title="Fitness Centre"></div>
CSS
.hotwire-fitness {
float: left;
margin-right: 5px;
background: url(/prostyle/images/new_amenities.png) -71px 0;
width: 21px;
height: 21px;
}
According to the W3C (see links above), the title attribute serves much of the same purpose as the alt attribute
Title
Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:
alt
The alt attribute is defined in a set of tags (namely, img, area and optionally for input and applet) to allow you to provide a text equivalent for the object.
A text equivalent brings the following benefits to your website and its visitors in the following common situations:
nowadays, Web browsers are available in a very wide variety of platforms with very different capacities; some cannot display images at all or only a restricted set of type of images; some can be configured to not load images. If your code has the alt attribute set in its images, most of these browsers will display the description you gave instead of the images
some of your visitors cannot see images, be they blind, color-blind, low-sighted; the alt attribute is of great help for those people that can rely on it to have a good idea of what's on your page
search engine bots belong to the two above categories: if you want your website to be indexed as well as it deserves, use the alt attribute to make sure that they won't miss important sections of your pages.
In this Yahoo Developer Network (archived link) article it is suggested that if you absolutely must use a background-image instead of img element and alt attribute, use ARIA attributes as follows:
<div role="img" aria-label="adorable puppy playing on the grass">
...
</div>
The use case in the article describes how Flickr chose to use background images because performance was greatly improved on mobile devices.
I think you should read this post by Christian Heilmann. He explains that background images are ONLY for aesthetics and should not be used to present data, and are therefore exempt from the rule that every image should have alternate-text.
Excerpt (emphasis mine):
CSS background images which are by definition only of aesthetic value
– not visual content of the document itself. If you need to put an
image in the page that has meaning then use an IMG element and give it
an alternative text in the alt attribute.
I agree with him.
As mentioned in other answers, there is no (supported) alt attribute for a div tag only for the img tag.
The real question is why you need to add the alt attribute to all background images for the site? Based on this answer, it will help you determine which route to take in your approach.
Visual/Textual: If you are simply attempting to add a textual fall back for the user if the image fails to load, simply use the title attribute. Most browsers will provide a visual tool tip(message box) when a user hovers over the image, and if the image is not loaded for whatever reason, it behaves the same as an alt attribute presenting text when image fails. This technique still allows for the site to speed up load times by keeping images set to backgrounds.
Screen Readers: The middle of the road option, this varies because technically keeping your images as backgrounds and using the title attribute approach should work as hinted above, "Audio user agents may speak the title information in a similar context." However this is not guaranteed to work in all cases, including some readers may ignore it all together. If you end up opting for this approach, you can also try adding in aria-labels to help ensure screen readers pick these up.
SEO/Search Engines: Here is the big one, if you were like me, you added your background images, all was good. Then months later the customer(or maybe yourself) realized that you are missing out on some prime SEO gold by not having alt's for your images. Keep in mind, the title attribute does not have any weight on search engines, from my research and as mentioned in an article here: https://www.searchenginejournal.com/how-to-use-link-title-attribute-correctly/. So if you are aiming for SEO, then you will need to have an img tag with the alt attribute. One possible approach is to just load very small actual images on the site with alt attributes, this way you get all the SEO and don't have to readjust the existing CSS in place. However this may lead to additional load time depending on the size and google does indeed look at the images path when indexing. In short if you are going this route, just accept what has to be done and include the actual images instead of using backgrounds.
The general belief is that you shouldn't be using background images for things with meaningful semantic value so there isn't really a proper way to store alt data with those images. The important question is what are you going to be doing with that alt data? Do you want it to display if the images don't load? Do you need it for some programmatic function on the page? You could store the data arbitrarily using made up css properties that have no meaning (might cause errors?) OR by adding in hidden images that have the image and the alt tag, and then when you need a background images alt you can compare the image paths and then handle the data however you want using some custom script to simulate what you need. There's no way I know of to make the browser automatically handle some sort of alt attribute for background images though.
This article from W3C tells you what they think you should do
https://www.w3.org/WAI/GL/wiki/ARIATechnique_usingImgRole_with_aria-label_forCSS-backgroundImage
and has examples here
http://mars.dequecloud.com/demo/ImgRole.htm
among which
<a href="http://www.facebook.com">
<span class="fb_logo" role="img" aria-label="Connect via Facebook">
</span>
</a>
Still, if, like in the above example, the element containing the background image is just an empty container, I personally prefer to put the text in there and hide it using CSS; right where you show the image instead:
<a href="http://www.facebook.com"><span class="fb_logo">
Connect via Facebook
</span></a>
.fb_logo {
height: 37px; width: 37px;
background-image: url('../gfx/logo-facebook.svg');
color:transparent; overflow:hidden; /* hide the text */
}
The classical way to achieve this is to put the text into the div and use an image replacement technique.
<div class"ir background-image">Your alt text</div>
with background-image beeing the class where you assign the background image and ir could be HTML5boilerplates image replacement class, below:
/* ==========================================================================
Helper classes
========================================================================== */
/*
* Image replacement
*/
.ir {
background-color: transparent;
border: 0;
overflow: hidden;
/* IE 6/7 fallback */
*text-indent: -9999px;
}
.ir:before {
content: "";
display: block;
width: 0;
height: 150%;
}
Here's my solution for Immediate fix:
Once the background image is removed the alt text will be visible from Img tag.
.alt-image {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
.background-image{
background:url("https://www.w3schools.com/images/picture.jpg") no-repeat;
width:100%;
height:500px;
position:relative;
}
<div role="img" aria-label="place alt text here" title="place alt text here" class="background-image">
<img src="" alt="place alt text here" class="alt-image"/>
</div>
Here's my solution to this type of problem:
Create a new class in CSS and position off screen. Then put your alt text in HTML right before the property that calls your background image. Can be any tag, H1, H2, p, etc.
CSS
<style type="text/css">
.offleft {
margin-left: -9000px;
position: absolute;
}
</style>
HTML
<h1 class="offleft">put your alt text here</h1>
<div class or id that calls your bg image> </div>
It''s not clear to me what you want.
If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute function for example:
IMG:before { content: attr(alt) }
If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.
Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?
You can achieve this by putting the alt tag in the div were your image will appear.
Example:
<div id="yourImage" alt="nameOfImage"></div>

Image replacement

I have a large div with the site header/logo as the background image. Is there anything wrong with putting a h2 tag containing the site title behind this using z-index, so that it would show if the user couldn't/didn't get the image for some reason? I know this is different to a standard [background on the h2 element] image replacement. (EDIT: Sorry maybe i'm not making it clear - i'm using a div background image not an IMG tag)
You should use the alt attribute of the img tag, so if the image isn't loaded for some reason, the text would appear.
This is exactly why the alt attr exists,.
If possible, I would ditch the div and just use an h2 with an id and set a background image to that.
I do that whenever possible to avoid excessive divs when I could use other block-level elements, if it only has a background and text. An h* with a background image is still a heading.
You can simple place img tag with alt attribute. That way if image is not loaded, text will be displayed.
<img src="" alt="This text will be displayed" />
Google doesn't like what you describe:
http://www.google.com/support/webmasters/bin/answer.py?answer=66353
However, from a pure design perspective, there is no real problem, save some bloated code.
You might want to see how often your images fail before you attempt any changes.
That's fine. Note that many feel the site logo isn't really something you'd put into an h* tag other than on the home page, when it makes sense to put it in an h1 tag.

CSS background image alt attribute

This is one I have not had to tackle before. I need to use alt tags on all images in a site including those used by CSS background-image attribute.
There is no CSS property like this as far as I know, so what is the best way to do this please?
Background images sure can present data! In fact, this is often recommended where presenting visual icons is more compact and user-friendly than an equivalent list of text blurbs. Any use of image sprites can benefit from this approach.
It is quite common for hotel listings icons to display amenities. Imagine a page which listed 50 hotel and each hotel had 10 amenities. A CSS Sprite would be perfect for this sort of thing -- better user experience because it's faster. But how do you implement ALT tags for these images? Example site.
The answer is that they don't use alt text at all, but instead use the title attribute on the containing div.
HTML
<div class="hotwire-fitness" title="Fitness Centre"></div>
CSS
.hotwire-fitness {
float: left;
margin-right: 5px;
background: url(/prostyle/images/new_amenities.png) -71px 0;
width: 21px;
height: 21px;
}
According to the W3C (see links above), the title attribute serves much of the same purpose as the alt attribute
Title
Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:
alt
The alt attribute is defined in a set of tags (namely, img, area and optionally for input and applet) to allow you to provide a text equivalent for the object.
A text equivalent brings the following benefits to your website and its visitors in the following common situations:
nowadays, Web browsers are available in a very wide variety of platforms with very different capacities; some cannot display images at all or only a restricted set of type of images; some can be configured to not load images. If your code has the alt attribute set in its images, most of these browsers will display the description you gave instead of the images
some of your visitors cannot see images, be they blind, color-blind, low-sighted; the alt attribute is of great help for those people that can rely on it to have a good idea of what's on your page
search engine bots belong to the two above categories: if you want your website to be indexed as well as it deserves, use the alt attribute to make sure that they won't miss important sections of your pages.
In this Yahoo Developer Network (archived link) article it is suggested that if you absolutely must use a background-image instead of img element and alt attribute, use ARIA attributes as follows:
<div role="img" aria-label="adorable puppy playing on the grass">
...
</div>
The use case in the article describes how Flickr chose to use background images because performance was greatly improved on mobile devices.
I think you should read this post by Christian Heilmann. He explains that background images are ONLY for aesthetics and should not be used to present data, and are therefore exempt from the rule that every image should have alternate-text.
Excerpt (emphasis mine):
CSS background images which are by definition only of aesthetic value
– not visual content of the document itself. If you need to put an
image in the page that has meaning then use an IMG element and give it
an alternative text in the alt attribute.
I agree with him.
As mentioned in other answers, there is no (supported) alt attribute for a div tag only for the img tag.
The real question is why you need to add the alt attribute to all background images for the site? Based on this answer, it will help you determine which route to take in your approach.
Visual/Textual: If you are simply attempting to add a textual fall back for the user if the image fails to load, simply use the title attribute. Most browsers will provide a visual tool tip(message box) when a user hovers over the image, and if the image is not loaded for whatever reason, it behaves the same as an alt attribute presenting text when image fails. This technique still allows for the site to speed up load times by keeping images set to backgrounds.
Screen Readers: The middle of the road option, this varies because technically keeping your images as backgrounds and using the title attribute approach should work as hinted above, "Audio user agents may speak the title information in a similar context." However this is not guaranteed to work in all cases, including some readers may ignore it all together. If you end up opting for this approach, you can also try adding in aria-labels to help ensure screen readers pick these up.
SEO/Search Engines: Here is the big one, if you were like me, you added your background images, all was good. Then months later the customer(or maybe yourself) realized that you are missing out on some prime SEO gold by not having alt's for your images. Keep in mind, the title attribute does not have any weight on search engines, from my research and as mentioned in an article here: https://www.searchenginejournal.com/how-to-use-link-title-attribute-correctly/. So if you are aiming for SEO, then you will need to have an img tag with the alt attribute. One possible approach is to just load very small actual images on the site with alt attributes, this way you get all the SEO and don't have to readjust the existing CSS in place. However this may lead to additional load time depending on the size and google does indeed look at the images path when indexing. In short if you are going this route, just accept what has to be done and include the actual images instead of using backgrounds.
The general belief is that you shouldn't be using background images for things with meaningful semantic value so there isn't really a proper way to store alt data with those images. The important question is what are you going to be doing with that alt data? Do you want it to display if the images don't load? Do you need it for some programmatic function on the page? You could store the data arbitrarily using made up css properties that have no meaning (might cause errors?) OR by adding in hidden images that have the image and the alt tag, and then when you need a background images alt you can compare the image paths and then handle the data however you want using some custom script to simulate what you need. There's no way I know of to make the browser automatically handle some sort of alt attribute for background images though.
This article from W3C tells you what they think you should do
https://www.w3.org/WAI/GL/wiki/ARIATechnique_usingImgRole_with_aria-label_forCSS-backgroundImage
and has examples here
http://mars.dequecloud.com/demo/ImgRole.htm
among which
<a href="http://www.facebook.com">
<span class="fb_logo" role="img" aria-label="Connect via Facebook">
</span>
</a>
Still, if, like in the above example, the element containing the background image is just an empty container, I personally prefer to put the text in there and hide it using CSS; right where you show the image instead:
<a href="http://www.facebook.com"><span class="fb_logo">
Connect via Facebook
</span></a>
.fb_logo {
height: 37px; width: 37px;
background-image: url('../gfx/logo-facebook.svg');
color:transparent; overflow:hidden; /* hide the text */
}
The classical way to achieve this is to put the text into the div and use an image replacement technique.
<div class"ir background-image">Your alt text</div>
with background-image beeing the class where you assign the background image and ir could be HTML5boilerplates image replacement class, below:
/* ==========================================================================
Helper classes
========================================================================== */
/*
* Image replacement
*/
.ir {
background-color: transparent;
border: 0;
overflow: hidden;
/* IE 6/7 fallback */
*text-indent: -9999px;
}
.ir:before {
content: "";
display: block;
width: 0;
height: 150%;
}
Here's my solution for Immediate fix:
Once the background image is removed the alt text will be visible from Img tag.
.alt-image {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
.background-image{
background:url("https://www.w3schools.com/images/picture.jpg") no-repeat;
width:100%;
height:500px;
position:relative;
}
<div role="img" aria-label="place alt text here" title="place alt text here" class="background-image">
<img src="" alt="place alt text here" class="alt-image"/>
</div>
Here's my solution to this type of problem:
Create a new class in CSS and position off screen. Then put your alt text in HTML right before the property that calls your background image. Can be any tag, H1, H2, p, etc.
CSS
<style type="text/css">
.offleft {
margin-left: -9000px;
position: absolute;
}
</style>
HTML
<h1 class="offleft">put your alt text here</h1>
<div class or id that calls your bg image> </div>
It''s not clear to me what you want.
If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute function for example:
IMG:before { content: attr(alt) }
If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.
Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?
You can achieve this by putting the alt tag in the div were your image will appear.
Example:
<div id="yourImage" alt="nameOfImage"></div>

When to use IMG vs. CSS background-image?

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
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
Use IMG if you intend to have
people print your page and you want the image to be included by default.
—JayTee
Use 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
Use 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
Use IMG if you rely on browser scaling to render an image in proportion to text size.
Use IMG
for multiple overlay images in IE6.
Use 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.
Using img instead of background-image can dramatically improve performance of animations over a background.
When to use CSS background-image
Use CSS background images if the
image is not part of the content.
—sanchothefat
Use CSS background images when
doing image-replacement of text eg. paragraphs/headers.
—sanchothefat
Use background-image if you intend to have
people print your page and you do not want the image to be included by default.
—JayTee
Use background-image if you need to improve download times, as
with CSS sprites.
Use background-image if you need for only a portion of the image to be visible, as with CSS sprites.
Use 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.
Above answers considers only Design aspect . I am listing it in SEO aspects.
When to use <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
When to use CSS background-image
Images Purely Used to Design.
No Relation With Content.
Small Images which we can play with CSS3.
Repeating Images ( In blog author icon , date icon will be repeated for each article etc.,).
As i will use them based on these reasons. These are Good practices of Search Engine Optimization of Images.
Browsers aren't always set to print background images by default; if you intend to have people print your page :)
If you have your CSS in an external file, then it's often convenient to display an image that's used frequently across the site (such as a header image) as a background image, because then you have the flexibility to change the image later.
For example, say you have the following HTML:
<div id="headerImage"></div>
...and CSS:
#headerImage {
width: 200px;
height: 100px;
background: url(Images/headerImage.png) no-repeat;
}
A few days later, you change the location of the image. All you have to do is update the CSS:
#headerImage {
width: 200px;
height: 100px;
background: url(../resources/images/headerImage.png) no-repeat;
}
Otherwise, you'd have to update the src attribute of the appropriate <img> tag in every HTML file (assuming you're not using a server-side scripting language or CMS to automate the process).
Also background images are useful if you don't want the user to be able to save the image (although I haven't ever needed to do this).
About the same as sanchothefat's answer, but from a different aspect. I always ask myself: if I would completely remove the stylesheets from the website, do the remaining elements only belong to the content? If so, I did my job well.
Some answers overcomplicate the scenario here. This is a dead simple situation.
Just answer to this question every time you'd like to place an image:
Is this part of the content or part of the design?
If you can't answer this, you probably don't know what you're doing or what you want to do!
Also, DO NOT consider beside the two technique, just because you'd wish to be "printer friendly" or not. Also DO NOT hide content from a SEO point of view with CSS. If you find yourself managing your content in CSS files, you shot yourself in the leg. This is just a trivial decision of what is content or not. Every other aspect should be ignored.
I would add another two arguments:
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.
Foreground = img.
Background = CSS background.
Use background images only when necessary e.g. containers with image that tiles.
One of the major PROS by using IMAGES is that it is better for SEO.
Using a background image, you need to absolutely specify the dimensions. This can be a significant problem if you don't actually know them in advance or cannot determine them.
A big problem with <img /> is overlays. What if I want an CSS inner shadow on my image (box-shadow:inset 0 0 5px rgb(0,0,0,.5))? In this case, since <img /> can't have child elements, you need to use positioning and add empty elements which equates to useless markup.
In conclusion, it's quite situational.
A couple of other scenarios where background-image should be used:
When you want the image to change when the mouse is hovered upon it.
When you want to add rounded corners to the image. If you use img, the image leaks out of the rounded corners.
Use CSS background-image in a case of multiple skins or versions of design. Javascript can be used to dynamically change a class of an element, which will force it to render a different image. With an IMG tag, it may be more tricky.
Here's a technical consideration: will the image be generated dynamically? It tends to be a lot easier to generate the <img> tag in HTML than to try to dynamically edit a CSS property.
What about the size of the image? If I use the img tag, the browser scales the image. If I use css background, the browser just cuts a chunk from the larger image.
img is an html tag for a reason, therefore it should be used. For referencing or to illustrate things, people e.g: in articles.
Also if the image has a meaning or has to be clickable an img is better than a css background. For all other situation, I think, a css background can be used.
Although, it is a subject that needs to be discussed over and over.
Web Student from Paris, France
In regards to animating images using CSS TranslateX/Y (The proper way to animate html) - If you do a Chrome Timeline recording of CSS background-images being animated vs IMG tags being animated you will see the paint times are drastically shorter for the CSS background-images.
There's another reason! If you have a responsive design and want to split usage of low, medium, and high-res images for devices through media queries, you should use backgrounds as well.
Also, i have a gallery section which has inconsistent picture sizes so even though those images are obviously considered content, I use background images and center them in divs with a set size. This is similar to what facebook does in their albums..
Just a small one to add, you should use the img tag if you want users to be able to 'right click' and 'save-image'/'save-picture', so if you intend to provide the image as a resource for others.
Using background image will (as far as I'm aware on most browsers) disable the option to save the image directly.
A small input,
I have had problems with responsive images slowing down the rendering on iphone for up to a minute, even with small images:
<!-- Was super slow -->
<div class="stuff">
<img src=".." width="100%" />
</div>
But when switching to using background images the problem went away, this is only viable if targeting newer browsers.
HTML is for content and CSS is for design. Is the image necessary and does it need to be picked up by screen readers? If the answer is yes, then put the image in the HTML. If it is purely for styling, then you can use the background-image property in CSS to inject the image. Just as a lot of people here have already mentioned, you can then use a pseudo element on the image if you like.
IMG load first because the src is in the html file itself whereas in the case of background-image the source is mentioned in stylesheet so the image loads after the stylesheet loaded, delaying the loading of the webpage.
Another background-image PRO: Background-images for <ul>/<ol> lists.
Use background images if they are part of the overall-design and are repeated on multiple pages. Preferably in background sprite form for optimization.
Use tags for all images that are not part of the overall design, and are most likely placed once, like specific images for articles, people, and important images that deserve to be added to google images.
** The only repeated image that I enclose in a <img> tag is the site/company logo. Because people tend to click it to go to the homepage, thus you wrap it with an <a> tag.
Also note that most search engine spiders don't index CSS background images therefore the background images will be ignored and you won't be able to get any traffic from search engines (no SEO benefit in short).
Where as all images defined with tags are indexed (unless manually excluded) and can bring in traffic from search engines if their title/alt attributes and filenames are optimized properly (w.r.t some keyword).
You can use IMG tags if you want the images to be fluid and scale to different screen sizes. For me these images are mostly part of the content. For most elements that are not part of the content, I use CSS sprites to keep the download size minimal unless I really want to animate icons etc.
I use image instead of background-image when i want to make them 100% stretchable which supported in most browsers.
If you want to add an image only for the special content on the page or for only one page the you should use IMG tag and if you want to put image on more than one pages then you should use CSS Background Image.