select nth-child from 1st to 4th

I which to reach the 4th first child. is there a better syntax than?

footer div:first-child, footer div:nth-child(2), footer div:nth-child(3), footer div:nth-child(4)  {display: inline-block;}

1 answer

  • answered 2018-01-14 10:01 Danield

    Yes, there's a better syntax.

    The selector you're looking for is: :nth-child(-n + 4)

    Here's a demo:

    .wpr {}
    
    .wpr div {
      width: 50px;
      height: 50px;
      background-color: red;
      display: inline-block;
      margin: 10px;
    }
    
    .wpr div:nth-child(-n + 4) {
      background-color: green;
    }
    <div class="wpr">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>

    See MDN - nth-child

    :nth-child(-n+3)

    Represents the first three elements among a group of siblings.