Blix
Blix

Reputation: 289

Styling elements based on sibling count in LESS

I have this Less mixin (courtesy of Lea Verou):
I would like to pass a variable of max-items (8) and based on this create the rule set below with a loop. So I don't have to repeat code for every number of child elements (1,2,3,4,...).

.list-elements-count-undefined-width() {
  /* one item */
  &:first-child:nth-last-child(1) {
    width: 100%;
  }

  /* two items */
  &:first-child:nth-last-child(2),
  &:first-child:nth-last-child(2) ~ li {
    width: 50%;
  }

  /* three items */
  &:first-child:nth-last-child(3),
  &:first-child:nth-last-child(3) ~ li {
    width: (100% / 3);
  }

  /* four items */
  &:first-child:nth-last-child(4),
  &:first-child:nth-last-child(4) ~ li {
    width: 25%;
  }

  /* five items */
  &:first-child:nth-last-child(5),
  &:first-child:nth-last-child(5) ~ li {
    width: 20%;
  }

  /* six items */
  &:first-child:nth-last-child(6),
  &:first-child:nth-last-child(6) ~ li {
    width: (100% / 6);
  }
} 

Upvotes: 0

Views: 1101

Answers (1)

Blix
Blix

Reputation: 289

.list-elements-count-undefined-width(@i) when (@i > 0) {
  .list-elements-count-undefined-width((@i - 1));
  &:first-child:nth-last-child(@{i}),
  &:first-child:nth-last-child(@{i}) ~ li{
    width: (100% / @i);
  }
}
.list-elements-count-undefined-width(8);

Upvotes: 3

Related Questions