dspano
dspano

Reputation: 1640

Can a sass selector contain a '%' character?

I have a variable that contains a string value in the form of some percentage eg. '10%' I want to use that value to build a class name to add to my html element if the percentage is anything above '0%'. I thought this would be easy using a sass loop but I can't seem to get the class name constructed correctly. I thought it would look something like this.

 @for $i from 1 through 100{
   .highlight-#{$i}% {
       // styling
    }
  }

  .highlight-0% {
      // styling
  }

I have tried several variations:

.highlight-#{$i + '%'} { // styling }
.highlight-#{$i}${'%'} { // styling }

I don't know if this is even possible since '%' may be reserved.

I am adding the html just in case someone can suggest a way to remove the % in there. This is what I would like to be able to do:

<tr><td class="pad-10 highlight-${publisher.numViewsPercentage}" align="center">${publisher.numViewsPercentage}</td></tr>

Upvotes: 2

Views: 608

Answers (2)

Brett DeWoody
Brett DeWoody

Reputation: 62743

Not only is % a reserved character in Sass, the bigger issue is it's not an allowed character in CSS selector names. So even if you could make Sass compile the resulting class names won't be valid and won't work.

For the most part selector names need to use only letters, numbers, underscore and hyphens.

.nopercent {
  color: red;
}

.percent% {
  color: red;
}
<div class="nopercent">
  An element withOUT a percent sign in the class.
</div>
<div class="percent%">
  An element with a percent sign in the class.
</div>

Upvotes: 4

Simon Kraus
Simon Kraus

Reputation: 736

% is a placeholder character in SASS since version 3.2. You should just use it for "invisible" extendeds.

Upvotes: 1

Related Questions