Bas
Bas

Reputation: 2210

Selecting every 1st element with nth-of-type

I've got this HTML markup:

<div class="parent">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
    <div class="child">5</div>
    <div class="child">6</div>
    <div class="child">7</div>
    <div class="child">8</div>
    <div class="child">9</div>
    <div class="child">10</div>

    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
    <div class="child">5</div>
    <div class="child">6</div>
    <div class="child">7</div>
    <div class="child">8</div>
    <div class="child">9</div>
    <div class="child">10</div>

    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
    <div class="child">5</div>
    <div class="child">6</div>
    <div class="child">7</div>
    <div class="child">8</div>
    <div class="child">9</div>
    <div class="child">10</div>
</div>

With these CSS properties:

.child {
    float: left;
    width: 10%;
    background-color: red;
}

As you can see, the classes with the content from 1 through 10 fill the screen in the width. And have a background-color of red.

I've got 3 of these, im going to call these 'rows'.

I have achieved to give every last item of the rows a background-colorof yellow by doing this:

.child:nth-of-type(10n) {
    background-color: yellow;
}

But whenever I try to do the same thing but then on the first item on every row, its not working:

.child:nth-of-type(1n) {
    background-color: yellow;
}

How do I give every first item of a row a background-color aswell without creating other HTML elements.

Demo here

Upvotes: 1

Views: 69

Answers (2)

pavel
pavel

Reputation: 27082

Because 1n means each.

.child:nth-of-type(10n+1) {
     background-color: green;
}

OR

.child:first-child, .child:nth-of-type(10n) + .child {
     background-color: green;
}

Upvotes: 3

Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13978

So you want to apply different color to the cells(0,11,21 and so on). Write your CSS like below. "N" will start from 0 and so on. It means (0*10 + 1), (1*10 + 1), (2*10 + 1). More Details about the nth-of-type CSS

 .child:nth-of-type(10n+1) {
  background-color: green;
 }

Fiddle Demo

Upvotes: 2

Related Questions