Gustavo Fulton Gustavo Fulton - 1 year ago 143
Sass (Sass) Question

SCSS variable class name

On my website, I'm constantly doing style="font-size: #ofpx;". However, I was wondering if there's a way to do it with scss so that, when I declare a class, it would also change the font size. For example:

<div class='col-lg-4 font-20'>whatever here</div>

and this would change my font-size to 20. If I did font-30, it would change my font-size to 30 and etc...

What I have so far:

.font-#{$fontsize} {
font-size: $fontsize;

Answer Source

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.

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.

If you're positive that you want to define font-size for each element within the HTML, 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 uses sass loops to automatically generate classes for integers within a range. For example:

@for $i from 1 through 100 {
  .font-#{$i} {
    font-size: #{$i}px;

This is not a good idea. Pragmatically speaking, it offers zero advantages over just using inline styles. Also, with large ranges your resulting file will be larger (which affects website load times).

Here is a runnable jsFiddle example of this technique.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download