Martin Beentjes
Martin Beentjes

Reputation: 132

Use classname to generate style properties

I am working on a little table which has several different paddings, I have to put them into a div to make it work.

But I am currently having alot of classes containing only padding: Xpx; where X corresponds to classname padding-20. I want to have just one class in my CSS which automatically can assign the correct amount of padding by it's classname.

Is this possible with CSS or is there JavaScript needed to make this work?

Thanks!

Upvotes: 3

Views: 121

Answers (1)

cнŝdk
cнŝdk

Reputation: 32145

You need JavaScript to do this.

Parse the Document to get all the nodes and for each node get the className attribute to extract the given padding values:

var all = document.getElementsByTagName("*");

for (var i = 0, max = all.length; i < max; i++) {
  var className = all[i].className;
  if (className !== '' && typeof className !== 'undefined') {
    var paddingValues = className.split('-');
    switch (paddingValues[1]) {
      case 'left':
        all[i].style.paddingLeft = paddingValues[2] + "px";
        break;
      case 'top':
        all[i].style.paddingTop = paddingValues[2] + "px";
        break;
      case 'right':
        all[i].style.paddingRight = paddingValues[2] + "px";
        break;
      case 'bottom':
        all[i].style.paddingBottom = paddingValues[2] + "px";
        break;
    }
  }

}
p,
div,
span {
  background-color: yellow;
}
<p>this a paragraph without any style</p>
<div class="padding-left-20">Blabla blabla</div>
<br>
<span class="padding-left-10">some text....</span>
<p class="padding-top-30">this a new paragraph</p>

Note:

I assume you will have all the classNames respecting this format :

padding-side-value

padding-top-30

padding-left-10

Upvotes: 2

Related Questions