基于兄弟节点的样式元素在LESS中计数

时间:2015-07-29 07:35:14

标签: less

我有这个Less mixin(由Lea Verou提供):
我想传递一个max-items(8)变量,并在此基础上用循环创建下面的规则集。因此,我不必为每个子元素(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);
  }
} 

1 个答案:

答案 0 :(得分:3)

.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);