Can I programmatically define a property value for a series of CSS classes?

I need help understanding an easier way to write this.

I have classes with a number between 1 and 100 at the end. For example:

.select1 {
    padding: 1em;
}

.select2 {
    padding: 2em;
}

.select3 {
    padding: 3em;
}

      

and etc.

I want to match the number to the amount I want to add, but don't know how to do it in CSS. Instead of writing them, is there a more object-oriented way to do this in CSS?

+3


source to share


2 answers


You can use a CSS preprocessor like SASS or LESS with variables.

For example, with SASS, you can do a for loop:

$class-slug: select !default

@for $i from 1 through 100
  .#{$class-slug}-#{$i}
    padding: $i + 0em

      



To display what you are looking for.

It's not a pure CSS solution, but it's better than doing each one by hand. Otherwise, you can also do it with Javascript, but this is not ideal.

+4


source


You cannot do this with CSS. And you shouldn't do that. It is similar to inline styles:

<div style="padding: 1em"></div>
<div style="padding: 2em"></div>
<div style="padding: 3em"></div>
...

      



Bad way. You have to separate HTML layout and CSS.

+2


source







All Articles