Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Generate Dynamic Classes Of Width, Margin, Padding Etc Using SCSS

Parent Feed: 

For using basic & common classes for grid layout (For width), typography, alignment etc, we write css like:

For alignment

.margin-top--5px { margin-top: 5px; } .margin-top--10px { margin-top: 10px; } .margin-top--15px { margin-top: 15px; } ...

Typography

.h1-32pt { font-size: 32pt; } .h2-28pt { font-size: 28pt; } .h3-24pt { font-size: 24pt; } .h4-20pt { font-size: 20pt; } ...

Grid views

.width-1 { width: 8.33%; } .width-2 { width: 16.66%; } .width-3 { width: 25%; } .width-4 { width: 33.33%; } ...

  • But with use of below code, all the classes with respective css are generated at once and we don't have to write each css manually.
  • User can generate classes for different properties like width, height, padding, margin, font-size, line-height, etc.
  • Main benefits are any numerical units like px, %, vw, vh, em, rem, etc can be used
  • Whole series of classes like above will be generated by using small code snippet.

Example of generated class with respective value

Ex, width: 10px , width: 15px , width: 20px , … , width: 100px , width: 200px , …

Below code generate CSS properties like:

.margin-top--0per {
  margin-top: 0%;
}
.margin-top--1per {
  margin-top: 1%;
}
.padding-all--0px {
  padding: 0px;
}
.padding-all--10px {
  padding: 10px;
}

Note: Our demo creating 1 to 100 value.

SCSS Code:

/**
 * Adding margin, padding & width classes.
 * Ex. margin-top--10px, padding-all--50per, width--100per
 */


/* Map for position */
$position-map: (
  top: 'top',
  right: 'right',
  left: 'left',
  bottom: 'bottom',
);


$unit-map: (
  per: '%',
  px: 'px',
);


@for $size from 0 through 100 {
  @each $unit, $ut in $unit-map {
    @each $position, $pos in $position-map {
      .margin-#{$position}--#{$size}#{$unit} { margin-#{$position}: #{$size}#{$ut}; }
      .padding-#{$position}--#{$size}#{$unit} { padding-#{$position}: #{$size}#{$ut}; }
    }


    .margin-all--#{$size}#{$unit} { margin: #{$size}#{$ut}; }
    .margin-vertical--#{$size}#{$unit} {
      margin-top: #{$size}#{$ut};
      margin-bottom: #{$size}#{$ut};
    }
    .margin-horizontal--#{$size}#{$unit} {
      margin-right: #{$size}#{$ut};
      margin-left: #{$size}#{$ut};
    }


    .padding-all--#{$size}#{$unit} { padding: #{$size}#{$ut}; }
    .padding-vertical--#{$size}#{$unit} {
      padding-top: #{$size}#{$ut};
      padding-bottom: #{$size}#{$ut};
    }
    .padding-horizontal--#{$size}#{$unit} {
      padding-right: #{$size}#{$ut};
      padding-left: #{$size}#{$ut};
    }


    .width--#{$size}#{$unit} {
      width: #{$size}#{$ut} !important;
    }
  }
}

So, this is a smart code - use it and save your time guys! Feel free to add your views and comments for any Drupal Development Services. #letstalksolution

Author: 
Original Post: