Is there any way to create dynamic utility classes in css?

Viewed 148

Is there any way to do something like... <h1 class="pad-5">Some Heading</h1> to apply a padding of 5px to the h1 tag. And this should be dynamic. For example, If I write class="pad-15", it should give padding of 15px.

And I want to do this by creating one single ruleset. Not by defining different classes of pad-5, pad-15 and so on individually.

In css file, it should be something like...

.pad-[$value]{
     padding: $value;
}

So, is there any way of doing this?

2 Answers

No, you cannot do this with CSS. You could use a CSS preprocessor such as SASS or Less to generate a bunch of classes for you in a loop if you want. You could alternatively use JS to add styling based on the class name, though I would definitely not recommend it.

SASS (SCSS) example:

@for $i from 1 through 15 {
    .pad-#{$i} {
        padding: $i;
    }
}
Related