0

I want to add a variable to a css class. Is it possile? I mean I want to do something like the following:

#box[i]
{
   padding: [i]px;
}

(for example: div which is name "box10" is supposed to get padding of 10px.)

I understand this may not be the right syntax, but I hope you can help me achieve the concept setting my class' properties up to a variable value.

3 Answers 3

1

It's currently not possible to use variables within CSS, however there are a number of other options available.

  • The simplest option would be to create a CSS style for each of your box IDs.
  • You could use JavaScript to add padding to the box, but it is not sensible to include presentation within logic. In jQuery, a loop to do this would look like (assuming your boxes are ):

    $('div[id^=box]').each(function() {
        $(this).css('padding',this.id.substr(3)+'px');
    });
    
  • You could use a pre-processor tool, such as LESS to set variables in your CSS; but you would still need to specify each selector.

Setting padding based on different box ID values seems like an odd problem to have. It may be worth taking a look at whether your approach to building this page is correct. Don't forget every ID on the page should be unique. If you wish to use the same ID on multiple elements, you should use CSS classes.

If you are trying to create a box sized based on a number of results (such as poll results), then it would be easier to use the style attribute and set a width/padding on each element rather than create an ID for every possible outcome. For example:

<div style="width:10px"></div>
Sign up to request clarification or add additional context in comments.

Comments

0

No, you can't do that with pure CSS, but you can use less for that.

CSS variables are introduced only in W3C draft at this point and didn't supported by browsers yet.

Comments

0

u could just use javascript, to detect the "name" and then get the substring so u have the number. then just make something like this:

var box = document.getElementByName("box10");
box.style.padding = box.name.substr(3) + "px";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.