Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use name of selector as value for a variable in SASS

I'd like to take the ID of a div that I'm applying styling to and set a variable to have that ID as its value. Is this something Sass can do? So the selector #eleven would set the value of a variable to "eleven".

Here's the current code. First a mixin that I'm using:

@mixin left-icon ($bgcolor, $bgurl, $iconmargin) {
    background: $bgcolor url(images/#{$bgurl}.png) no-repeat left 5px center;
    & h2, & p {margin-left: $iconmargin;}
}

And this is when I call the mixin:

#eleven {
    @include left-icon(#de4c3f,eleven,$defaulticonmargin);
}

So when I used that mixin there's a background color, part of a file name, and a value for margins (which are added to some child selectors) that are set. As you can see the $bgurl variable matches the selector's name. Basically I want to automate that so that the $bgurl will be set to the text string from the ID (with the hash symbol stripped).

The reason being that I'm going to have dozens of boxes with the same basic pattern but unique background image and it seems, in my head, the simplest thing to do would be to save each PNG using the ID name as the file name and then let Sass match them up. I could just do as I have done here and put the value in longhand but it seems like something Sass might do so I'd rather spend time getting it right and learning more about Sass than do half a job.

Hope that makes sense and isn't a ridiculously stupid question – I will admit (and you won't be surprised to hear) that I'm a very raw Sass recruit but I figure I can learn from this question.

like image 876
user3717789 Avatar asked Oct 20 '22 07:10

user3717789


1 Answers

Try something like this:

@mixin left-icon ($bgcolor, $bgurl, $iconmargin) {
  ##{$bgurl} {
    background: $bgcolor url(images/#{$bgurl}.png) no-repeat left 5px center;
& h2, & p {margin-left: $iconmargin;}
  }
}

@include left-icon(#de4c3f,eleven,10px);

Basically, you can add variables anywhere using Sass's interpolation syntax

like image 193
Pezholio Avatar answered Oct 28 '22 16:10

Pezholio