Dani
Dani

Reputation: 4187

Take number from class using Sass

Having the class name 'class-name-X' (where X might be a number from 0 to 9) I'd like to create an specific class for all of them like:

.class-name-{X} {
  height: {X} + 'px';
}

Is that possible? I know that using arrays it's but this comes from the JS to the HTML so on the CSS I only get the class name

Upvotes: 5

Views: 5626

Answers (1)

Terry
Terry

Reputation: 66133

You can use the @for directive to iterate through numbers (say 0 through 9 in your use case), and use string interpolation to inject the current index as part of the class name, and also to the width property:

$start: 0;
$end: 9;

@for $i from $start through $end {
  .class-name--#{$i} {
    width: #{$i}px;
  }
}

Remember that SASS is a pre-compile language, so you will need to compile it and then use that generated CSS for your page ;)

Upvotes: 10

Related Questions