5
votes

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.

2
Yes, only just came back to this. Pezholio's solution does exactly what I need. I will have a look at implementing yours too but its not wholly clear to me how it answers the problem – that's a limitation with my knowledge and hopefully I'll learn more about SASS by trying your versionuser3717789

2 Answers

3
votes

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

0
votes

What you could do instead to make it simpler is use IDs or classes called b11 (or bg11, the letters are arbitrary)

$colorArray = [ #de4c3f, ... ];
@for $i from $min through $max {
    .b#{$i} {
        @include left-icon(colorArray[$i], $i, $defaulticonmargin);
    }
}

and then change the background names to match the new format, as in images/#11.png or you can use this process to convert the string to an int

This way you can define all of your elements recursively!