CMSCSS
CMSCSS

Reputation: 2176

CSS: Can't get multiple :nth-child selectors to work

I have a main menu and 4 colours and Id like each colour to cycle through 1-4 then start again if there are more than 4 items.

But each menu item only receives the first colour - this is my CSS (compiled from less):

.main-nav li a:nth-child(4n+1) {
  background-color: #7ebdeb;
}
.main-nav li a:nth-child(4n+2) {
  background-color: #abc081;
}
.main-nav li a:nth-child(4n+3) {
  background-color: #f4d1a2;
}
.main-nav li a:nth-child(4n+4) {
  background-color: #e96956;
}

I have no other background colours specified - I've been racking my brain and have tried several online nth-child testers to double check the specific selectors but can't work out what's going wrong sorry.

Upvotes: 1

Views: 330

Answers (2)

Markus Kottländer
Markus Kottländer

Reputation: 8268

I guess this is what you want:

JSFiddle

.main-nav li:nth-child(4n+1) a {
  background-color: #7ebdeb;
}
.main-nav li:nth-child(4n+2) a {
  background-color: #abc081;
}
.main-nav li:nth-child(4n+3) a {
  background-color: #f4d1a2;
}
.main-nav li:nth-child(4n+4) a {
  background-color: #e96956;
}

Upvotes: 0

j08691
j08691

Reputation: 207891

You are targeting the same element in each list item, the anchor, repeatedly. Each list item only has one child. You probably want:

.main-nav li:nth-child(4n+1) {
    background-color: #7ebdeb;
}
.main-nav li:nth-child(4n+2) {
    background-color: #abc081;
}
.main-nav li:nth-child(4n+3) {
    background-color: #f4d1a2;
}
.main-nav li:nth-child(4n+4) {
    background-color: #e96956;
}

jsFiddle example

Upvotes: 4

Related Questions