Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using nth child to target every other TWO divs

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

like image 771
Francesca Avatar asked Jan 28 '26 21:01

Francesca


2 Answers

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

like image 191
Chowlett Avatar answered Jan 30 '26 19:01

Chowlett


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!

like image 35
Arkadiusz Lendzian Avatar answered Jan 30 '26 19:01

Arkadiusz Lendzian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!