Search code examples
csscss-selectorspseudo-class

Using CSS nth-child to select irregular pattern in sequence


I need to select the following in sequence with CSS3 nth-child if possible but can't figure out how to...

70% Width

1, 4, 5, 8, 9, 12, 13, 16, 17, 20

(+3+1r)

30% Width

2, 3, 6, 7, 10, 11, 14, 15, 18, 19

(+1+3r)

I can only see a way of selecting the same increment in sequence (i.e 1, 5, 9, 13, 17) so wondered if anyone could advise of a few single rules to select as per the above or whether I would require some overlapping rules that override as necessary.


Solution

  • Using nth-child(4n+0) and nth-child(4n+1) in combination should select the required elements.

    1, 4, 5, 8, 9... would be selected by the above combination while the other sequence is the remaining items. So set the 30% width as default and over-ride to 70% on the selected nth-child combinations.

    div{
        background: green;
    }
    div:nth-child(4n+0),
    div:nth-child(4n+1){
        background: red;
    }
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
    <div>10</div>
    <div>11</div>
    <div>12</div>
    <div>13</div>
    <div>14</div>
    <div>15</div>
    <div>16</div>
    <div>17</div>
    <div>18</div>
    <div>19</div>
    <div>20</div>
    <div></div>