Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

padding

less

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!

like image 548
Jani Avatar asked Dec 04 '18 11:12

Jani


People also ask

How do you use the nth element using the CSS selector?

The :nth-of-type(n) selector matches every element that is the nth child, of the same type (tag name), of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-child() selector to select the element that is the nth child, regardless of type, of its parent.

How do I select all 3 children in CSS?

formula (an + b) In addition to the value n being able to be any number, you can also use a formula. nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one.

What's the difference between the nth of type () and Nth child () selector?

As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .


1 Answers

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

}
<div class="parent">
  <div>0</div>
  <div>15</div>
  <div>30</div>
  <div>45</div>
  <div>60</div>
  <div>75</div>
</div>
like image 199
Temani Afif Avatar answered Nov 15 '22 04:11

Temani Afif