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

Matthew Stewart
Matthew Stewart
9,214 Points

Benefits of using images in CSS versus putting them into HTML?

I was just watching one of the videos in the CSS deep dive and noticed that the instructor used an image in the CSS and put a couple in his HTML. I was just curious if there are any benefits of using one over the other when it comes to including an image in your site.

Guil Hernandez
Guil Hernandez
Treehouse Teacher

Matthew Stewart,

Like James Barnett mentioned, img should be used for contextual imagery that need alt attributes for accessibility.

Other things to keep in mind:

  • If you give img a display: none; the browser will still load it.
  • If you give a display: none; to an element that has a background image, the bg image will not be loaded by the browser.
  • img elements can't generate pseudo-elements because they are replaced elements.

2 Answers

Use img when:

  • If the image is part of the content, has alt text or needs to be printed

Use background-image when:

  • The image is a background, part of the layout or shouldn't be printed

source: http://uvu.miketheindian.com/2011/09/28/img-vs-background-image/

Typically you will almost always have a mixture of both. You typically put images that are not part of the layout in HTML (maybe minus things like your logo and social link that is on each page) and put your background or layout images in your CSS.

Personally I use image sprites to help with load time and server requests so I load all of my layout images via css with background images. It doesn't take long after you start building websites for this concept of what type of image goes where to start to sink in and make more sense.

Also something to remember is that everyone has their own style when it comes to developing sites. Where I may use image sprites others may not use sprites at all and that is ok. You will develop your own style and way of doing things.