0

Is it possible to create a sass, scss, or css selector that could take a value in the selector and apply it to the style?

Example (with wrong syntax since I don't know how to do it:

.w(\d+) {
   width: $1% ;
}

In the above example,

.w100 => width: 100%
.w82 => width: 82%

and so on.

Jeff
  • 4,285
  • 15
  • 63
  • 115
  • There's attribute selectors which can be used to accomplish something similar. eg `[class^=w]` – admcfajn Jan 05 '21 at 18:48
  • Can you take the value from match and apply it to width for example? – Jeff Jan 05 '21 at 18:51
  • No, but you could use [css-variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) - Those won't work in IE though – admcfajn Jan 05 '21 at 18:57
  • Here's a couple other resources i found with a quick search, what you're aiming for looks quite doable with a scss function/mixin https://stackoverflow.com/questions/22249527/sass-match-number-in-class-name - https://stackoverflow.com/questions/16126448/sass-compass-getting-variable-name-from-variable/16126625#16126625 – admcfajn Jan 05 '21 at 19:01

1 Answers1

1

you can use @for loop to do this.

Example:

@for $i from 1 through 100 {
    .w#{$i} {
        width: $i * 1%;
    }
}

this loop will generates below css as output:

.w1 {
  width: 1%;
}

.w2 {
  width: 2%;
}

.w3 {
  width: 3%;
}

.w4 {
  width: 4%;
}

.
.
.
.w100 {
  width: 100%;
}