Prashant Kumar
Prashant Kumar

Reputation: 21

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

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?

Upvotes: 2

Views: 474

Answers (2)

Chris Yungmann
Chris Yungmann

Reputation: 1269

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;
    }
}

Upvotes: 3

symlink
symlink

Reputation: 12208

Use a mixin (with Sass):

https://sass-lang.com/documentation/at-rules/mixin

Example:

@mixin pad($width) {
  padding: #{$width}px;
}

Application:

h1{
  @include pad(5);
}

Upvotes: 1

Related Questions