I'm trying to use nth child to select every other TWO divs.
This means, when there is a collection of divs 1, 2, 3, 4, 5, and 6 - I need to select 1, 2, 5 and 6. Every other two.
CSS:
#navigation .menuItem:nth-child(3n+3) {
background-color: #ccc;
}
HTML:
<div class="menuItemWrapper">
<div class="menuItem"><a href="shop.html">Shop Online</a></div>
<div class="menuItem"><a href="blog.html">The Blog</a></div>
<div class="menuItem"><a href="lookbook.html">LookBook</a></div>
<div class="menuItem"><a href="gift-finder.html">Gift Finder</a></div>
<div class="menuItem"><a href="about.html">About Us</a></div>
<div class="menuItem sub"><a href="freebies.html">Tutorials</a></div>
<div class="menuItem sub"><a href="faq.html">FAQ</a></div>
<div class="menuItem sub"><a href="contact.html">Contact</a></div>
JS Fiddle
You won't be able to do it with a single selector, but you can with two:
#navigation .menuItem:nth-child(4n+1), #navigation .menuItem:nth-child(4n+2) {
background-color: #ccc;
}
Fiddle
There is a simple hack for this:
Firstly: set global color for your lined-up <div>s
.menuItemWrapper>div { background-color: #fff; }
Secondly: select every 4th element and apply alternative background to <div> element directly after it. That makes pairs. -1 to begin from the right place.
.menuItemWrapper>div:nth-child(4n-1) { background-color: #ccc; }
.menuItemWrapper>div:nth-child(4n-1)+div { background-color: #ccc; }
Enjoy!
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