Home > Software design >  How to get this nth-child()
How to get this nth-child()

Time:09-28

How can we use nth-child() to have the following style, where the first column has no style, the second transform: translateY(20px), the third transform: translateY(40px) and the third transform: translateY(60px).

There is no div column, all the cards are displayed and arranged using flex.

enter image description here

.wrapper{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  height: 100vh;
  
}

.card{
  height: 50px;
  width: 20%;
  background: teal;
  margin: 10px;
}

.card:nth-child(2n){
  transform: translateY(20px);
}
.card:nth-child(3n){
  transform: translateY(40px);
}
.card:nth-child(4n){
  transform: translateY(60px);
}
<div >

<div >1</div>
<div >2 - translateY(20px)</div>
<div >3 - translateY(40px)</div>
<div >4 - translateY(60px)</div>
<div >5</div>
<div >6 - translateY(20px)</div>
<div >7 - translateY(40px)</div>
<div >8 - translateY(60px)</div>
<div >9</div>
<div >10 - translateY(20px)</div>
<div >11 - translateY(40px)</div>
<div >12 - translateY(60px)</div>

</div>

CodePudding user response:

The problem is that for the sixth element the .card:nth-child(3n) selector overrides the .card:nth-child(2n) selector because 6 is dividable by 2 and 3. The same happens for 8 and 12.

Instead you can use 4n for every selector and add the offset for each column.

.wrapper{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  height: 100vh;
  
}

.card{
  height: 50px;
  width: 20%;
  background: teal;
  margin: 10px;
}
 
.card:nth-child(4n   2){
  transform: translateY(20px);
}
.card:nth-child(4n   3){
  transform: translateY(40px);
}
   .card:nth-child(4n   4){
  transform: translateY(60px);
<div >

<div >1</div>
<div >2 - translateY(20px)</div>
<div >3 - translateY(40px)</div>
<div >4 - translateY(60px)</div>
<div >5</div>
<div >6 - translateY(20px)</div>
<div >7 - translateY(40px)</div>
<div >8 - translateY(60px)</div>
<div >9</div>
<div >10 - translateY(20px)</div>
<div >11 - translateY(40px)</div>
<div >12 - translateY(60px)</div>

</div>

CodePudding user response:

Your pattern repeat each 4 elements so you need 4n x

.wrapper{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  height: 100vh;
  
}

.card{
  height: 50px;
  width: 20%;
  background: teal;
  margin: 10px;
}

.card:nth-child(4n   2){
  transform: translateY(20px);
}
.card:nth-child(4n   3){
  transform: translateY(40px);
}
.card:nth-child(4n   4){
  transform: translateY(60px);
}
<div >

<div >1</div>
<div >2 - translateY(20px)</div>
<div >3 - translateY(40px)</div>
<div >4 - translateY(60px)</div>
<div >5</div>
<div >6 - translateY(20px)</div>
<div >7 - translateY(40px)</div>
<div >8 - translateY(60px)</div>
<div >9</div>
<div >10 - translateY(20px)</div>
<div >11 - translateY(40px)</div>
<div >12 - translateY(60px)</div>

</div>

  • Related