SCSS variable class name

This can’t be done for arbitrary sizes. The nature of SCSS is that is needs to be flattened down to CSS before it gets applied to the HTML. What you are asking for, however, is essentially to create rules at run-time rather than compile-time.

In other words, SCSS makes it easier to write some of the repetitive parts of CSS, but it doesn’t allow you to do anything new that wasn’t already possible with plain old CSS.

What you’re asking for is also a code smell. It smells like your markup isn’t semantic enough. The purpose of a CSS class is to group objects with similar characteristics, but you’re using them instead to describe the styles they impart. I would suggest stepping back and reconsidering what it is that you really want.

You obviously have details of certain elements that are context-dependent. For example, maybe you are applying these rules to buttons when you want to make them smaller or larger than usual. You need to identify the scenarios in which the buttons change. Maybe they are 20% smaller if they are in a modal dialog? Then write your normal .button rules, and also create rules for .modal .button which make it smaller.

If you’re positive that you want to define font-size for each element within the HTML (and sometimes there are good reasons for doing so), just continue using inline styles. The only reason inline styling is frowned upon is because it combines model and view logic in a way that harms reusability; however, what you are requesting does so in exactly the same way. This is what inline styles were made for. Don’t re-invent the wheel.

With all of that said, you can use sass loops to automatically generate classes for integers within a range. For example:

/* warning: this is generally a bad idea */
@for $i from 1 through 100 {
  .font-#{$i} {
    font-size: #{$i}px;
  }
}

This is not a good idea. Pragmatically speaking it doesn’t offer any advantages over just using inline styles and with large ranges your resulting file will be larger (which affects website load times).


Aside: There is a CSS philosophy (or fad, if you’re feeling ungenerous) called Atomic CSS (or sometimes Functional CSS) which defies the classical advice given in this answer. I won’t give an opinion on its effectiveness at producing clean, maintainable code, but it does typically require more tooling than SCSS alone if used with the degree of specificity requested in this question.

Leave a Comment