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

Scss: how to change the background url dynamically based on class?

Is it possible to change the background url based on the class with scss?

For example:

.c-page-foot__link--twitter {
    background-image: url('../img/ic-twitter.svg');
}
.c-page-foot__link--facebook {
    background-image: url('../img/ic-facebook.svg');
}

How can I rewrite this so I don't have to repeat the same code for each social media icon? So I would like to change the part after ic- with the last part of the class name.

1 Answer

Hi Julie,

I think you could use a mixin to make this work:

The mixin should look like this:

@mixin bgimage($name) {
  $url:"../images/#{$name}.png";
  background: url($url);
}

And then you could pass the name with an include statement:

@include bgimage(your-png-file-without-extension);