I'm trying to use nth-child to change background colors of divs. Below is an image of how I want to change the background colors. How would I do this with nth-child?
Each box should be 25% width of it's parent container.
In order for the nth-child rules you've declared to work after a user clicks to hide divs, you need to remove the hidden divs from the DOM, so they no longer exist as siblings.
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .
Since it's a repeating pattern over 8 elements, you can use that to create the CSS:
div:nth-child(8n+1),
div:nth-child(8n+3),
div:nth-child(8n+6),
div:nth-child(8n) {
background-color:black
}
div:nth-child(8n+2),
div:nth-child(8n+4),
div:nth-child(8n+5),
div:nth-child(8n+7) {
background-color:gray
}
Fiddle: http://jsfiddle.net/RvbsL/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With