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 How to Make a Website Adding Pages to a Website Add Iconography

Gabriele Rossi
Gabriele Rossi
5,887 Points

background-image vs. <img>

Hi, I hope this question is not too obvious. I was wondering why, to add icons, we would use a background image for the

<a>

element and then "push it to the side" with padding and margin, rather than adding an

<img>

tag before each of the

<a>

links...

3 Answers

Tim Knight
Tim Knight
28,888 Points

Gabriele,

I think for me it's not so much just about semantic meaning, but flexibility. As I see it, icons don't really serve semantic value alone, they have some type of label that identifies them which is likely some form text or attribute. They're an assistive visual element for between visual recognition. Where I believe that using background images in CSS really shines is that it gives you the flexibility for theming your site. Everything related to the style and layout would be within your CSS. If you changed your CSS to reflect a darker style you could adjust those icons from within that same sheet without modifying the markup unnecessarily.

Gabriele Rossi
Gabriele Rossi
5,887 Points

Oh I see, that actually makes a lot of sense as well. Thank you Tim!

Depends on what you're trying to do. But in the case of the course it's to eliminate the additional item I guess. There are some instances where one works better than the other and that's your judgement call. But as a general rule of thumb, if the image has significant semantic meaning, like a warning icon or a logo use the img tag. Use background images as the name hints for backgrounds and additional fluff.

Gabriele Rossi
Gabriele Rossi
5,887 Points

Thank you Ali, that actually makes sense. I guess I just found the "add&squeeze" approach somewhat counterintuitive.

If you use background-image, you can take a JavaScript free approach to changing the image (often used for icons with a hover effect)

Gabriele Rossi
Gabriele Rossi
5,887 Points

Thank you Rick! Wow, all of these answers are really good. I didn't think there would be so many reasons to do this. I thought it might just have been for simplicity/consistency.