When to use IMG vs. CSS background-image?
Asked Answered
I

31

777

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.

Iong answered 29/1, 2009 at 18:25 Comment(7)
Do you need the image to take up space or do you want to write over it?Stewpan
As an update, since this ranks pretty high on Google, browser scaling and image stretching for background-image is now possible, and pretty widely supported (IE8 and below, of course, being the exception), rendering items 4 and 7 moot in cases that can allow for a fallback or ignoring such an effect for IE8 and below. caniuse.com/#search=background-imageNicki
great and useful post, i'll add a question for the comparison, the advantage of the css is also the hover effects? can this be replicated using img tags?Tiger
I generally add both the alt attribute and the title attribute to all content images. Is this not preferable?Herdsman
Also img can have map with clickable areas and hintsDamocles
@Damocles You can apply hints (titles) to many other elements, other than imgs, if that's what you mean?Yaroslavl
u were wrong in mentioning css sprite with background-image makes it better over IMG tag. No, in the case of IMG same thing can be acheived using CSS Clip property so remove these points from the Pro's of Background-image.Tritheism
I
926

Proper uses of IMG

  1. Use IMG if you intend to have people print your page and you want the image to be included by default. —JayTee
  2. 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

  1. 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
  2. Use IMG if you rely on browser scaling to render an image in proportion to text size.
  3. Use IMG for multiple overlay images in IE6.
  4. 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.
  5. Using img instead of background-image can dramatically improve performance of animations over a background.

When to use CSS background-image

  1. Use CSS background images if the image is not part of the content. —sanchothefat
  2. Use CSS background images when doing image-replacement of text eg. paragraphs/headers. —sanchothefat
  3. 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
  4. Use background-image if you need to improve download times, as with CSS sprites.
  5. Use background-image if you need for only a portion of the image to be visible, as with CSS sprites.
  6. Use background-image with background-size:cover in order to stretch a background image to fill its entire window.
Iong answered 23/9, 2009 at 23:58 Comment(20)
I'm still iffy on the background images for text replacement part. I see people using background-images then using text-indent: -9999px for the text. However I know having text indents like this used to be bad for SEO and I'd imagine it still must be for some search engines. But most important, if you turn images off but leave css on the image dissapears but the text is still off the screen. As far as I am concerned the alt text on an image is for if images are not displays so img tags are better.Compiler
I agree with Scott Reed on text replacement. The key is should the image be displayed when printing. In the case of text replacement, it should.Hebbe
I don't agree that the IMG tag is better for animating. If you do some testing in chrome animating elements around using css translate, you will see the paint times are drastically shorter for css background-image vs the IMG tagRenown
Pragmatic Use of backbround image: When you don't want to loose hair about vertical centering problems (of images of varying vertical size) ;)Shrewd
Yes, vertical centering problems - bring on Flexbox!Obannon
Flexbox still isn't really viable, if you're trying to reach the "whole" market. Might work for small sites/clients but on bigger ones its just not an acceptable approach at the time of this writing (unless your client specifically decides to cut out certain browsers)Lannie
I would add this to the "pragmatic" list: If you remove the CSS styles from the page (e.g. kill your stylesheet links), do you see a bunch of confusing UI arrows and goofy widget images, etc, and, conversely, do things like the site logo, content images, etc, disappear? If no to both, you're doing well. If yes to both, you should consider image tags.Lannie
See also the answer about loading time and comment below : in some cases using CSS background may be an issue in terms of display delays.Malawi
What about the goal of separating style from content? I don't want to edit the CSS if I add to a page an image that is supposed to be a background to some div. It feels to me like there should be some way of inserting background images in the HTMLPoorhouse
@BinaryFunt - <div class="my-css-page-styles" style="background-image:url(blah.png);"></div> That way you can style it in your CSS stylesheet but if the background image is more a question of content than style then you're still editing it from the HTML side of things.Lethargy
Those seem like good guidelines and yet I see so many sites that don't follow them. Is there any other reasons you're missing? Are there other reasons those designer might not be using img tags? Example: Scroll down this page to the packages section with a rocket being loaded. The rocket is a background image. Any rational reason why or just designer preference?Arly
background-image was helpful for me for two reasons: background-size: cover and the ability to overlay a gradient overtop an imageBandog
I suppose another pragmatic use of background-image is if you need to bundle your image content using a tool like webpack. IMGs also seem a little bit easier to use inline with text than boxes with background-image.Maharajah
Isn't there a semantic argument to be had here for creating readable HTML that accurately describes what's being rendered? For example, if you see <img> in code, you know there's going to be an image there. Whereas if you see <div> and the fact that it has an image is buried in another file somewhere, that seems like inefficient grokability. Just thinking out loud, could you still use <img> tag with no src and apply the background-image through CSS - or is that crazy talk?Urinate
There seems to be a clickbait in point 5 of pragmatic uses of IMG - pointing to a japanese blog post about cosmetics. the link is www.ajaxline.com/browsers-performance-in-dependence-of-html-coding [DO NOT CLICK THIS]Quinquefid
@Patrick in revision 2, you deleted a link to some content by roborouke, and added a second mention of JayTee's discussion of printing. Was that intentional?Xyster
@Andrew That was five years ago, I have no idea. :)Biaxial
Thanks for all use of image background. is it possible to use a part of image as background and repeat it in x or y direction? suppose if we have an image sprite with different patterns and want to apply different patterns on different sections by avoiding more http requests?Arana
Css background-images #6: there is no need for css backgrounds since object-fit can do this for html images. Also consider css background-images has some unique options: it supports tiling (repeat, repeat-x, repeat-y) and does support (tiling) gradients. Css background-images also supports multiple layers (images are gradients) that you can resize, tile and position at will.Partizan
Nice question @MikeBartlett! I've read on <img> specs that src is required. You can use a custom html tag, to achieve the same result! There's a nice article here that explains how. You can use a span without issue anyway. A tip you may find useful: choose html components by their features first (e.g.: a button has "click" event; a checkbox has a "selected: true/false" state, etc..), then you can use CSS to adapt its aspect to your needs!Inattention
A
312

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.

Archy answered 29/1, 2009 at 18:31 Comment(13)
Excellent case! CON--Use background-image when doing image-replacement of text.Iong
Yeah, it's never ideal to do image replacement but some designs just won't be right until you do.Archy
+1 agreed. Note that image replacement of text falls in the same "not part of the content", since the content is the actual text.Assegai
Doesn't a background-image have to be attached to something? You have to add some content to add a background to it and at the moment you can only have 1 background per content element...Hystero
perfect answer but there is one exception: the site logo, so you make sure its printed.Relapse
This is a fair point, but surely the image-replacement of text (e.g. for a heading) would require you to add an "alt" in order for screen readers to read it? Or in case images are not displayed you still get the heading? Yes, a heading and then styled would be better, but surely you want the text?Loux
@Relapse I mentioned the logo as being content ;)Archy
@TheoScholiadis using image replacement does not mean using an image instead of text, but hiding the text in some way using CSS and supplying the image as a background using CSS. The document remains semantically untouched.Archy
Personally I hate when I can't copy "text" because it's actually an image. Call me lazy but hey...Tetragon
Pretty much sums it up, I like to approach these decisions by treating HTML as "data" and CSS as "view" - so if it's informative and relevant to that particular page then use IMG; if it's purely theme/layout-related then use CSSIcelandic
When you need image for SEO purpose, then use img tag with alt attribute. Otherwise use image in background using css.Absorptance
It's interesting that you use "logo" as an example of an image that is part of the content. Surely a company logo is an example of a background image, just as it is on paper?Karolkarola
It's probably worth distinguishing between how the logo is used, too. A company logo in the <nav> should arguably be a background-image. If the website lists apps made by the company, each app logo in this list should arguably be a regular image.Reena
M
120

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.

Marymarya answered 29/1, 2009 at 18:25 Comment(3)
That's not a good reason. You could have a div with 2 overlayed images, and the following css: #some_div { transition: opacity 0.5s; }, #some_div:hover #top_img { opacity: 0; }Washable
If you read that linked MDN article (or the w3c specs), you will find that background-image is NOT one of the properties that is animatable, and any browser that does so (chrome), isn't following the web standards. That said, I think it should be, and it's a nice easy effect so I'm disappointed that it isn't part of the standard.Tal
@RobertMcKee well since there's only chrome now lolIncorporated
D
92

Above answers considers only Design aspect . I am listing it in SEO aspects.

When to use <img />

  1. When Your Image need to be indexed by search engine
  2. 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.
  3. List item
  4. If your image is not too small ( not iconic images ).
  5. Images where you can add alt and title attribute.
  6. Images from a webpage which you want to print using print media css

When to use CSS background-image

  1. Images Purely Used to Design.
  2. No Relation With Content.
  3. Small Images which we can play with CSS3.
  4. 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.

Dildo answered 29/1, 2009 at 18:25 Comment(0)
F
57

Browsers aren't always set to print background images by default; if you intend to have people print your page :)

Feodore answered 29/1, 2009 at 18:32 Comment(2)
Sounds like: PRO--Use IMG if you want the image to print by default. CON--Use background-image if you don't want the image to print by default. Nice one!Iong
I think the idea is to have separate print-only CSS styles which hide the images or change them to something more appropriate.Kathlyn
P
53

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).

Potentate answered 10/4, 2009 at 6:18 Comment(4)
Background images can certainly be saved with some minimal view source spelunking, just not as easily as right-clicking on an image.Emileeemili
Firefox. Right-click. "View background image". Not that difficult.Maisey
@Maisey Unless there's a transparent overlay or page-specific context menu modification to prevent you from doing that. I've seen that before, and in my opinion it's quite silly because you don't even need to go spelunking in source, if the page has fully loaded then in Firefox at least you can click Tools>Page Info/alt+t, i/right-click and select View Page Info, browse to the Media section, and save all the items you want from the list. Of course, there are ways to prevent even that, like embedding the image in a Flash file or other weird tricks, but even those can be bypassed or accounted for.Enoch
I think the background technique is not quite good for denied an user to save the image...Elaelaborate
S
50

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.

Scholasticism answered 20/4, 2009 at 17:1 Comment(0)
F
46

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.

Falsity answered 29/1, 2009 at 18:25 Comment(1)
I like this answer. It is very clear. The remaining issues like printer-friendly or SEO should be individually considered in each scenario.Spider
C
28

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.

Collinsworth answered 29/1, 2009 at 18:25 Comment(4)
This is a really good answer, particularly the resize point. People will argue that you can use background-size but if you're trying to support old browsers it's not necessarily the best way to go.Lannie
This is how it is done in CSS background-size: 80px 80px;Anacreon
Thank you @Kareem. I see this was introduced with CSS3, which did not yet exist when I originally answered. I have edited my answer to reflect this.Collinsworth
I think it important to note that resizing photos can be tricky in terms of pixelization or interpolation. When possible, I would not resize more than 40% ( and that's a stretch - 20% is standard) without bringing your image into a photo imaging software to properly be resized without losing quality. DPI quality can be important here if there is not enough information to stretch and fill the allotted amount of pixels.Marillin
V
23

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.

Vincents answered 29/1, 2009 at 18:25 Comment(1)
background-images ALT values can be defined in the sitemap. google.com/schemas/sitemap-image/1.1Anacreon
A
19

Foreground = img.

Background = CSS background.

Amabelle answered 22/5, 2009 at 18:3 Comment(2)
Sure, but what about the little down-arrow indicator next to the "menu" button, or other such elements. How do you classify that- foreground or background?Lannie
@Lannie I would say foreground, because they're (visually) in the "top" layer of the page, superimposed on other elements.Shouldst
A
14

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.

Amphibious answered 29/1, 2009 at 18:25 Comment(2)
Probably because you can use the alt attribute.Gather
Doesn't that depend on whether you WANT SEO for that specific image? I don't see why you would go for SEO on an image that is part of the styling of the page, not the content (e.g. an email icon on your contact page). So actually, I'd rather turn your statement around. Only use IMAGES when necessary (that being content-related, print-related and/or SEO-related).Clingfish
B
13

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.

Backstage answered 29/1, 2009 at 18:25 Comment(0)
I
11

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.
Iaea answered 29/1, 2009 at 18:25 Comment(2)
You can actually do: img { border-radius: 10px; }Curch
@RafcioKowalsky you are correct. Can't remember the exact conditions in which border-radius was not working.Bharal
M
11

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.

Minster answered 13/2, 2009 at 18:29 Comment(2)
you can dynamically change the src attribute of an image tag too, just as easy as changing a classArchy
@sanchothefat, true, however, in this case image source would need to be kept in JS instead of CSS. IMO css file would be more appropriate to keep file name.Minster
C
8

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

Coquet answered 29/1, 2009 at 18:25 Comment(0)
P
7

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.

Positively answered 29/1, 2009 at 18:25 Comment(3)
maarten, terscheling is not Pipeable I heard from Vincent willems. So how do you think it can work on PyMolInterlocutor
Please refer to the documentation as to how pipeable it is pieterpeitshoeve.nl/rondleidingPositively
@Maarteen, i guess now that can be done using html 5 picture and source tagsLiggett
R
7

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.

Renown answered 29/1, 2009 at 18:25 Comment(0)
M
7

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.

Meed answered 2/2, 2009 at 22:30 Comment(3)
And what about inline styles? This question really must not decided by this idea.Scholasticism
maybe I should phrase is this way: would you rather work with a DOM element or an element attribute?Meed
probably worth considering bacl in '09, but with jQuery this is hardly an issue. It's even easier and more fluid to switch css or classes on an element, than switching elements.Glosseme
P
7

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.

Potvaliant answered 22/5, 2009 at 18:0 Comment(0)
H
6

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..

Halflife answered 29/1, 2009 at 18:25 Comment(0)
P
5

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.

Paternoster answered 29/1, 2009 at 18:25 Comment(2)
Do you have any support for or explanation of this behavior?Sourdough
Sorry, i have no idea why it would slow down the page to a crawl.. maybe the re-flow in the browser on iphone have very little resources.Paternoster
A
5

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.

Audit answered 29/1, 2009 at 18:25 Comment(0)
T
4

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.

Tritheism answered 29/1, 2009 at 18:25 Comment(1)
Plus some browsers (e.g. Firefox 35) seem to refresh CSS background-image after some time : if you have several tabs opened, when you go back to your tab after some time the CSS background is blank for a while.Malawi
C
4

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.

Canonize answered 29/1, 2009 at 18:25 Comment(0)
O
3

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).

Orbicular answered 29/1, 2009 at 18:25 Comment(0)
D
3

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.

Deandra answered 29/1, 2009 at 18:25 Comment(0)
C
2

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.

Caste answered 29/1, 2009 at 18:25 Comment(0)
E
2

I use image instead of background-image when i want to make them 100% stretchable which supported in most browsers.

Evelyn answered 29/1, 2009 at 18:25 Comment(0)
L
2

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.

Listed answered 29/1, 2009 at 18:25 Comment(0)
A
0

Just to throw a spanner in the works - i'm of the opinion that you should never use the img tag. HTML was meant for content, not visual style. all the images on your page should come from the CSS, leaving your HTML code pure. (even if it does take a bit longer to build)

Alliber answered 29/1, 2009 at 18:25 Comment(3)
I agree with you with regard to images that serve as page decorations, but surely some images are content: photographs in a news article, or diagrams in an academic article, etc. Those are part of the content, and probably warrant an IMG tag.Tiller
that would be more valid if there were no advantages to the tag, but currently, you get more power/control with the tag and cannot consider making it obsolete.Tiger
"leaving your HTML code pure" -- Have you ever come onto a project where every image is a background image? Let me tell you - it's enfuriating on a project that is undocumented (most projects) and you have basically random decisions being made about what element is used to place the background image. The WC3 web specification has defined the image tag since the beginning of the internet. Semantics define that you use the img tag where appropriate. It is my belief that you over-complicate and significantly reduce code maintainability by putting everything into CSS like that.Lannie

© 2022 - 2024 — McMap. All rights reserved.