[html] When to use IMG vs. CSS background-image?

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.

This question is related to html css image background-image

The answer is


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.

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.


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.


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.


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.


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.


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


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.


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.


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.


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


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.


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


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.


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.


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 not to design.
  3. If your image is not too small ( not iconic images ).
  4. Images where you can add alt and title attribute.
  5. 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.


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


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.


Foreground = img.

Background = CSS background.


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)


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


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.


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.


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.


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.


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 not to design.
  3. If your image is not too small ( not iconic images ).
  4. Images where you can add alt and title attribute.
  5. 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.


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)


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.


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.


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.


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.


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.


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.


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.


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


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.


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.


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.


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


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.


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


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.


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.


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


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.


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.


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


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.


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


Foreground = img.

Background = CSS background.


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.


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.


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.


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.


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


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.


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.


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.


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.

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


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


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.


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.


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.


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.


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to background-image

How to add a color overlay to a background image? CSS: stretching background image to 100% width and height of screen? CSS blur on background image but not on content Adding background image to div using CSS How to apply a CSS filter to a background image How to use responsive background image in css3 in bootstrap Responsive background image in div full width Overlay a background-image with an rgba background-color Is there a way to set background-image as a base64 encoded image? Using HTML data-attribute to set CSS background-image url