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

2019-08-11 01:50发布

问题:

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.

回答1:

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



回答2:

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;
}