When to use IMG vs. CSS background-image?

422,813

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

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.

Solution 5

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

Share:
422,813
system PAUSE
Author by

system PAUSE

/** * Default constructor * INPUT PARAMETERS: none * INPUT/OUTPUT PARAMETERS: none * RETURNS: n/a * * Initializes the instance. */ UselessCommentsDemo::UselessCommentsDemo() : data( NULL ) { } /** * Destructor * INPUT PARAMETERS: none * INPUT/OUTPUT PARAMETERS: none * RETURNS: n/a * * Does nothing. */ UselessCommentsDemo::~UselessCommentsDemo() { } /** * Copy constructor * INPUT PARAMETERS: * other -- an instance of this class * INPUT/OUTPUT PARAMETERS: none * RETURNS: n/a * * Initializes the new instance as a copy of the other instance. */ UselessCommentsDemo::UselessCommentsDemo(const UselessCommentsDemo&amp; other) { this-&gt;data = other.data; }

Updated on August 05, 2022

Comments

  • system PAUSE
    system PAUSE almost 2 years

    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.

  • system PAUSE
    system PAUSE over 15 years
    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!
  • system PAUSE
    system PAUSE over 15 years
    Excellent case! CON--Use background-image when doing image-replacement of text.
  • roborourke
    roborourke over 15 years
    Yeah, it's never ideal to do image replacement but some designs just won't be right until you do.
  • roborourke
    roborourke about 15 years
    you can dynamically change the src attribute of an image tag too, just as easy as changing a class
  • MK_Dev
    MK_Dev about 15 years
    @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.
  • eglasius
    eglasius about 15 years
    +1 agreed. Note that image replacement of text falls in the same "not part of the content", since the content is the actual text.
  • viam0Zah
    viam0Zah about 15 years
    And what about inline styles? This question really must not decided by this idea.
  • Mesh
    Mesh about 14 years
    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...
  • learner
    learner over 13 years
    maybe I should phrase is this way: would you rather work with a DOM element or an element attribute?
  • benzado
    benzado over 13 years
    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.
  • Michael Hackner
    Michael Hackner over 13 years
    Background images can certainly be saved with some minimal view source spelunking, just not as easily as right-clicking on an image.
  • Katya Appazova
    Katya Appazova about 13 years
    perfect answer but there is one exception: the site logo, so you make sure its printed.
  • Scott Reed
    Scott Reed about 13 years
    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.
  • Evan Moran
    Evan Moran about 12 years
    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.
  • Theo Scholiadis
    Theo Scholiadis about 12 years
    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?
  • roborourke
    roborourke about 12 years
    @meo I mentioned the logo as being content ;)
  • roborourke
    roborourke about 12 years
    @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.
  • eivers88
    eivers88 over 11 years
    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 tag
  • Frank Nocke
    Frank Nocke about 11 years
    Pragmatic Use of backbround image: When you don't want to loose hair about vertical centering problems (of images of varying vertical size) ;)
  • ericosg
    ericosg about 11 years
    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.
  • TRiG
    TRiG about 11 years
    Firefox. Right-click. "View background image". Not that difficult.
  • David
    David almost 11 years
    Probably because you can use the alt attribute.
  • JAB
    JAB almost 11 years
    @TRiG 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.
  • ncubica
    ncubica almost 11 years
    I think the background technique is not quite good for denied an user to save the image...
  • Shaz
    Shaz almost 11 years
    Personally I hate when I can't copy "text" because it's actually an image. Call me lazy but hey...
  • Blazemonger
    Blazemonger over 10 years
    I think the idea is to have separate print-only CSS styles which hide the images or change them to something more appropriate.
  • Volzy
    Volzy about 10 years
    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).
  • Todd
    Todd almost 10 years
    Do you have any support for or explanation of this behavior?
  • winthers
    winthers almost 10 years
    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.
  • Rafff
    Rafff almost 10 years
    You can actually do: img { border-radius: 10px; }
  • Behrang
    Behrang almost 10 years
    @RafcioKowalsky you are correct. Can't remember the exact conditions in which border-radius was not working.
  • Mehdi Nellen
    Mehdi Nellen over 9 years
    maarten, terscheling is not Pipeable I heard from Vincent willems. So how do you think it can work on PyMol
  • Maarten
    Maarten over 9 years
    Please refer to the documentation as to how pipeable it is pieterpeitshoeve.nl/rondleiding
  • Dean_Wilson
    Dean_Wilson over 9 years
    Yes, vertical centering problems - bring on Flexbox!
  • dudewad
    dudewad over 9 years
    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)
  • dudewad
    dudewad over 9 years
    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.
  • dudewad
    dudewad over 9 years
    "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.
  • dudewad
    dudewad over 9 years
    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?
  • dudewad
    dudewad over 9 years
    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.
  • Mark K Cowan
    Mark K Cowan about 9 years
    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 CSS
  • Skippy le Grand Gourou
    Skippy le Grand Gourou about 9 years
    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.
  • Skippy le Grand Gourou
    Skippy le Grand Gourou about 9 years
    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.
  • dfherr
    dfherr almost 9 years
    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.
  • binaryfunt
    binaryfunt almost 9 years
    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 HTML
  • Jimbo Jonny
    Jimbo Jonny over 8 years
    @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.
  • gman
    gman over 8 years
    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?
  • Tom Grant
    Tom Grant over 8 years
    background-image was helpful for me for two reasons: background-size: cover and the ability to overlay a gradient overtop an image
  • jkdev
    jkdev almost 8 years
    @dudewad I would say foreground, because they're (visually) in the "top" layer of the page, superimposed on other elements.
  • Juan Herrera
    Juan Herrera almost 8 years
    I like this answer. It is very clear. The remaining issues like printer-friendly or SEO should be individually considered in each scenario.
  • killthrush
    killthrush almost 8 years
    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.
  • Kareem
    Kareem almost 8 years
    background-images ALT values can be defined in the sitemap. google.com/schemas/sitemap-image/1.1
  • Kareem
    Kareem almost 8 years
    This is how it is done in CSS background-size: 80px 80px;
  • Anders Rabo Thorbeck
    Anders Rabo Thorbeck almost 8 years
    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.
  • Mike Bartlett
    Mike Bartlett over 7 years
    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?
  • wick3d
    wick3d about 7 years
    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]
  • Billu
    Billu about 7 years
    When you need image for SEO purpose, then use img tag with alt attribute. Otherwise use image in background using css.
  • oligan
    oligan almost 7 years
    @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?
  • Cédric Guillemette
    Cédric Guillemette almost 7 years
    @Andrew That was five years ago, I have no idea. :)
  • dale landry
    dale landry almost 7 years
    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.
  • warkentien2
    warkentien2 almost 7 years
    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; }
  • Robert McKee
    Robert McKee almost 7 years
    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.
  • Tinu Jos K
    Tinu Jos K over 4 years
    @Maarteen, i guess now that can be done using html 5 picture and source tags
  • Hasan Baig
    Hasan Baig about 3 years
    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?
  • Tomas
    Tomas almost 3 years
    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?
  • metatron
    metatron almost 3 years
    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.
  • Christian Matthew
    Christian Matthew over 2 years
    @RobertMcKee well since there's only chrome now lol
  • funder7
    funder7 over 2 years
    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!
  • minerva
    minerva almost 2 years
    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.