Search code examples
css-selectors

Target 2 elements in CSS in a list


In a ul/li of 20 elements, how to target 2 concurrent elements out of 4 elements starting with the 2nd in the list (1 / 2+3 / 4 / 5 / 6+7 / 8 / 9 / 10+11 etc).

I try with the :nth-child rule but I can't do it. I can't find a rule with different values.

Regards. Jean


Solution

  • You can simply combine two CSS selectors to accomplish this. Comma separated CSS selectors will both be matched separately for the rules block.

    li {
      border: 1px solid black;
      padding: 1rem;
    }
    
    li:nth-child(4n+2), li:nth-child(4n+3) {
      background-color: #ffcccc;
    }
    <ul id="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
    </ul>