How to add different CSS style to every nth element, depending on n using LESS

江枫思渺然 提交于 2019-12-30 20:58:32

问题


I am trying to add different padding to subsequent elements in a div. My DOM looks pretty simple.

<div class="parent">
   <div>0</div>
   <div>15</div>
   <div>30</div>
   ...
</div>

So I would like for my first element to have 0 padding, my second 15, third 30 etc. Using LESS, how could I make this work? I have tried:

.parent div:nth-of-type(n) {
           padding-left: n*15px;
}

Thank you!


回答1:


Using less(but you have to set the num of elements):

.parent (@indexstart,@index) when (@indexstart < @index ){
  div:nth-child(@{indexstart}){
    padding-left: (@indexstart - 1) * 15px;
  }
  .parent (@indexstart + 1,@index);
}
.parent (1,4);

See example




回答2:


I suppose you want to achieve a stair visually. In this case you can do it like below:

.parent {
  line-height: 1.2em;
}

.parent>div:not(:first-child)::before {
  content: "";
  float: left;
  width: 15px; /*your padding*/
  height: calc(1.2em + 2px);
  
  background: #f2f2f2; /*To illustrate the stair effect*/
}
<div class="parent">
  <div>0</div>
  <div>15</div>
  <div>30</div>
  <div>45</div>
  <div>60</div>
  <div>75</div>
</div>


来源:https://stackoverflow.com/questions/53611853/how-to-add-different-css-style-to-every-nth-element-depending-on-n-using-less

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!