Vyas Rao
Vyas Rao

Reputation: 498

Select nth child select 1, 2, 5, 6, 9, 10 etc

I have a set of divs as follows,

<div class="selector">
    <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>

I want to provide background colour to divs 1,2,5,6,9,10 etc. How do I select the particular divs using nth selector? Is it possible?

PS: The number of divs may grow to n.

Upvotes: 5

Views: 4680

Answers (4)

davidcondrey
davidcondrey

Reputation: 35983

This equation will give you the sequence..

2n+[((-1)^(n+1))-3]/2

Upvotes: 0

Romeo Ching
Romeo Ching

Reputation: 18

I think by using nth-child is not good because of IE8 compatibility. Its better to use + sign li + li or by adding class each of div.

Upvotes: -2

Vucko
Vucko

Reputation: 20834

If I understood you correctly, you want to select:

1 2 3 4 5 6 7 8 9 10 ...
+ +     + +     +  + ...

For that you can use:

.selector>div:nth-child(4n+1), .selector>div:nth-child(4n+2){
    background-color:red;
}
<div class="selector">
    <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>

Thanks @SureshPonnukalai for the JSFiddle.

Upvotes: 17

KiV
KiV

Reputation: 2263

You can use nth child concept for this.

div.selector:nth-child(2) {
    background: #ff0000;
} 

Upvotes: -1

Related Questions