Alen
Alen

Reputation: 203

Apply Display to Certain nth-child

I want to display all nth-child with the value less than or equal to 4. Is there an if statement for CSS that will apply on the condition I want to display?

Thanks

Upvotes: 2

Views: 69

Answers (2)

Oriol
Oriol

Reputation: 288000

Yes. :nth-child accepts an n parameter which will take all non-negative integer values.

:nth-child(-n+4)
  • n=0: selects 4th child
  • n=1: selects 3th child
  • n=2: selects 2nd child
  • n=3: selects 1st child
  • n>3: nothing

Example:

div {
  margin: 10px;
}
div:nth-child(-n+4) {
  background: green;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>

Upvotes: 3

choz
choz

Reputation: 17858

You can still use :nth-child to achieve this.

E.g. This will select all first four children of lis inside of ul

ul > li:nth-child(-n+4)
{
  color: red;
}
<ul>
  <li> 1 </li>
  <li> 2 </li>
  <li> 3 </li>
  <li> 4 </li>
  <li> 5 </li>
  <li> 6 </li>
  <li> 7 </li>
</ul>

Upvotes: 3

Related Questions