Use class name to create style properties

I am working on a small table that has several different paddings, I have to place them in a div to make it work.

But I currently have a lot of classes containing only padding: Xpx;

where X matches the class padding-20

. I only want to have one class in my CSS that can automatically assign the correct amount of padding with this class.

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

Thank!

+3


source to share


1 answer


For this you need JavaScript

.

Parse the document to get all the nodes and for each node get the attribute className

to retrieve the specified 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>
      

Run codeHide result




Note:

I am assuming you will have all the class names related to this format:

padding-side value

upholstery-top-30

upholstery left-10

+2


source







All Articles