Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Less mixin for all 4 margins (top,right,bottom.left)

How can I write this css as an less mixin that generate all those classes automatically:

  .class1x{margin-top:1px;}
  .class2x{margin-right:1px;}
  .class3x{margin-bottom:1px;}
  .class4x{margin-left:1px;}
===========================================
  .class1y{margin-top:2x;}
  .class2y{margin-right:2px;}
  .class3y{margin-bottom:2px;}
  .class4ymargin-left:2px;}    
===========================================
  .class1n{margin-top:n..px;}
  .class2n{margin-right:n..px;}
  .class3n{margin-bottom:n..px;}
  .class4nmargin-left:n..px;}  

And to increment that classes and value, for example, until value is 100px. I have this less but I don't want to multiply for every css property:

@iterations: 30;
.loopingClass (@index) when (@index > 0) {
  .classx@{index} { /*classx the class to add in html*/
    margin: ~"@{index}px"; 
  }
  .loopingClass(@index - 1);
}
.loopingClass (0) {}
.loopingClass (@iterations); 

ty.

like image 792
BurebistaRuler Avatar asked Dec 11 '13 10:12

BurebistaRuler


People also ask

How do you set the top left and bottom right of a margin?

The syntax for the CSS margin property (with 2 values) is: margin: top_bottom left_right; When two values are provided, the first value will apply to the top and bottom of the element. The second value will apply to the left and right sides of the element.

How do I reduce margins in CSS?

Adjusting the Margin Size of an HTML Element With CSS You can remove this margin by setting the top and left margin to zero. Like the padding and border, the sizes of specific sides of the margin can be set using margin-left , margin-right , margin-top , and margin-bottom .

How do I change the margin of all sides in CSS?

You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

How many values a margin style rule Cannot?

Syntax. The margin property may be specified using one, two, three, or four values. Each value is a <length> , a <percentage> , or the keyword auto . Negative values draw the element closer to its neighbors than it would be by default.


1 Answers

Same solution as given by @Bass Jobsen, just gently optimized (it did not have to be so verbose):

// usage:

.class {
    .make-margins(3);
    // or:
    // .make-margins(10, px);
    // .make-margins(50, rem);
    // etc.
}

// implementation:

.make-margins(@i, @u: px) when (@i > 0) {
    .make-margins((@i - 1), @u);
    &@{i} {.margin-x(unit(@i, @u))}
}

.margin-x(@value) {
    &-1 {margin-top:    @value}
    &-2 {margin-right:  @value}
    &-3 {margin-bottom: @value}
    &-4 {margin-left:   @value}
}
like image 149
seven-phases-max Avatar answered Nov 02 '22 10:11

seven-phases-max