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 CSS Selectors Advanced Selectors Pseudo-Elements - ::before and ::after

:before or background image for small 'label' images

In this video guil uses the ::before psuedo element to enter the image labels for the jpg and zip files.

However earlier in the course he used the method of setting the background image as the image and then applying padding so it functions basically the same.

I was just wondering if either of these methods are considered a best practice or if they are simply down to preference!

Thanks for your time.

3 Answers

Giuseppe Nardella
Giuseppe Nardella
17,790 Points

I'll try. The pseudo-elements ::before and ::after create new contents in the page and you can style them as all other elements in the page. If you have an ul like this:

<ul>
  <li>Buy milk</li>
  <li>Take the dog for a walk</li>
  <li>Exercise</li>
  <li>Write code</li>
</ul>

you can insert a hyphen before li elements and style them.

li {
  list-style-type: none;
  position: relative;
  margin: 2px;
  padding: 0.5em 0.5em 0.5em 2em;
}

li::before {
  content: "ยป";
  color: red;
  height: 1em;
  top: 1.3em;
  left: 0.6em;
  margin-top: -1em;
  margin-right: 1em;
  padding-left: 1em;
}

If you use background image, this isn't a new content; you're applying the background proprerty for that element.

Thank you that makes sense! :)

Giuseppe Nardella
Giuseppe Nardella
17,790 Points

It depends on what is the purpose of the image.

If you use the method of setting a background image for label, this is only a style for the label.

Instead, if you use ::before, you create a new content for the page and you can style it and interact with it.

I hope I was clear

Thanks for the response, could you possibly elaborate on what more you can do with the image as content as opposed to a style?

You have a lot less control on images inserted with ::before/::after compared to background-image. See https://teamtreehouse.com/community/unable-to-resize-images-created-using-the-before-pseudoelement for more.