Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a css class that has dynamic value?

Tags:

css

Assume that I have some div elements like these:

<div class="mystyle-10">Padding 10px</div>

<div class="mystyle-20">Padding 20px</div>

<div class="mystyle-30">Padding 30px</div>

Is it possible to create a class or something like :

.mystyle-*{padding: *px; margin-left: *px; border: *px solid red; }

that will replace the * with the value we set for the div's class?

Thanks in advance!

like image 415
Nấm Lùn Avatar asked Nov 01 '22 03:11

Nấm Lùn


2 Answers

as @bjb568 said, you can easily achieve that using css pre-processors ( Sass, Less, Stylus .. etc )

below a Sass example

@for $i from 1 through 5 {
    .mystyle-#{ $i * 10 } {
        $result: ( $i * 10 ) + 0px;
        padding: $result;
        margin-left: $result;
        border: $result solid red;
    }
}

which will output the following:

.mystyle-10 {
    padding: 10px;
    margin-left: 10px;
    border: 10px solid red;
}

.mystyle-20 {
    padding: 20px;
    margin-left: 20px;
    border: 20px solid red;
}

.mystyle-30 {
    padding: 30px;
    margin-left: 30px;
    border: 30px solid red;
}

.mystyle-40 {
    padding: 40px;
    margin-left: 40px;
    border: 40px solid red;
}

.mystyle-50 {
    padding: 50px;
    margin-left: 50px;
    border: 50px solid red;
}
like image 164
Anas Nakawa Avatar answered Nov 12 '22 16:11

Anas Nakawa


You can target those elements with this selector - [class^="mystyle-"], but the rest is not possible with plain CSS.

like image 29
Ilya I Avatar answered Nov 12 '22 16:11

Ilya I