Vinicius Silveira
Vinicius Silveira

Reputation: 27

Use variables when declaring css classes or html divs

I need to create indefinite divs in my html code, and they differ from each other only by one feature (size, for example).

So, what I am doing right now is to use many css classes, each with the size I need for each div, and one class that contains the rest of my div's style, declaring it as <div class="class1 class2"></div>.

I am looking for a way to incorporate a variable in my css or html to avoid the declaration of a lot of classes, making possible to change the size directly in the code, as an example:

CSS
html { ... } 
.name {
 ...
content: ...;
font: ...;
border: ...;
}

.name_($var) {
 ...
height: ($var);
width: ($var);
}

HTML    
<div class="name name_10"></div> //div 1 size is 10px 10px
<div class="name name_20"></div> //div 2 size is 20px 20px
<div class="name name_50"></div> //div 3 size is 50px 50px
<div class="name name_80"></div> //div 4 size is 80px 80px

This way, it would be possible to have as many divs as I want and it wouldn't be necessary to create one class for each. Is there any way to achieve this only by css and html?! If not, what could help me getting this with jq or js?

Thank you in advance, guys!

Upvotes: 0

Views: 1371

Answers (3)

Sebastian Nette
Sebastian Nette

Reputation: 7832

You could also try something ugly like this:

function addCSS(name, css) {
    var style = document.getElementById("css");
    style.innerHTML += (name + " {" + css + "}");
}

var size = 20;
addCSS(".div1", "background:red; font-size:" + size + "pt;");
<style id="css"></style>

<div class="div1">div</div>

Upvotes: 1

Stu Furlong
Stu Furlong

Reputation: 3629

With regular old CSS, you can't do this. You should look into SASS or LESS if you want to start getting into CSS variables and functions like this (plus some other neat stuff).

You could do inline it with jQuery if you feel comfortable inlining your CSS and using JS for it.. it's not great but does the job. :

<div class="name name_10"></div>
<div class="name name_20"></div>

jQuery:

$('.name').each(function(){  
    var $this = $(this),
         size = $this.attr('class').split('_')[1]; // Split the number from the class

    $this.css({
       'width' : size + 'px',
       'height' : size + 'px'
    });
});

Although this might be overkill, you could just manually inline them at this point.

Upvotes: 1

Ole Sauffaus
Ole Sauffaus

Reputation: 534

If you really only need different sizes, or other simple css-differences, then make one master-class for all your generated divs, AND in Javascript (or backend) set that class + an inline style with the single attribute that differs.

... ending with HTML like this:

<div class="name" style="height:10px"></div>
<div class="name" style="height:20px"></div>

That way you can do all the work in JS (or at backend), and your markup is still fairly simple.

Upvotes: 1

Related Questions