Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Paul Barron
Paul Barron
6,595 Points

<img> tag vs. div background-image in css

Is there any advantage or disadvantage to using a div's background image, as opposed to using the actual <img> tag?

3 Answers

Good question Paul Barron

<img> is a HTML tag. It has a purpose that is to display images on a web document.

Purpose: Accessibility. When text based user agent renders the page alt attribute will be use. By default, browsers are not always set to print background image, so you using img tag will be beneficial.

When you use background image property in CSS it is a property to style the document. You can use CSS background property to set image when images are not part of document. It is merely for presentation.

background image property improve performance over img tag.

Hi Paul,

One advantage of adding images using css is that you can make the image stationary while the content scrolls. The css would look something like this:

body {
  background-image: url("img/image.jpg");
  background-attachment: fixed;
}

Jeff

Markus Ylisiurunen
Markus Ylisiurunen
15,034 Points

Hi Paul!

As Jeff said, you can do some pretty nice stuff with backgrounds. You can see the full reference what you can do at here. It's also a lot harder to save a background image to users computer than a regular image.

By using <img> instead of backgrounds you can add for example alt attribute to your image. It makes your SEO better and provides an alternative solution to show if your image isn't available.

Those are few things that popped to my mind. Hopefully it was at least a little helpfull :)