Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick nth-child issue

I've a quick :nth-child issue that I'm struggling to solve. I'm aiming to target every 3rd and 4th item in a grouping of 4 items that form a list.

For example:

<div class="normal">Item 1</div>
<div class="normal">Item 2</div>
<div class="different">Item 3</div>
<div class="different">Item 4</div>
<div class="normal">Item 5</div>
<div class="normal">Item 6</div>
<div class="different">Item 7</div>
<div class="different">Item 8</div>

In this example I'd like to target all instances of <div class="different"> - i've used a lot of nth-child generators to come up with an answer but nothing gets me to what I need.

Any help would be much appreciated!

like image 670
abbas_arezoo Avatar asked Dec 15 '14 15:12

abbas_arezoo


People also ask

How to select class nth child in CSS?

Definition and Usage. 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.

Why use nth child CSS?

The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.

How nth child work?

nth-child is a selector that matches every nth child element of its parent. Say you want to apply CSS to only a specific number of p elements. nth-child is exactly what you need. The above CSS will change the color of only the first p when the user hovers over nameContainer .

How to select nth child in jQuery?

jQuery :nth-child() SelectorThe :nth-child(n) selector selects all elements that are the nth child, regardless of type, of their parent. Tip: Use the :nth-of-type() selector to select all elements that are the nth child, of a particular type, of their parent.


1 Answers

Use div:nth-child(4n-1), div:nth-child(4n). The logic is simple — you want to select items in groups of four, so 4n would be the common denominator. Since you want to select the penultimate and the last items in the group, 4n-1 and 4n respectively would do the job.

As follow is a simple diagram illustrating my point:

#1
#2
#3  <- 4th item - 1
#4  <- 4th item
#5
#6
#7  <- 4th item -1
#8  <- 4th item

div:nth-child(4n-1), div:nth-child(4n) {
  background-color: #eee;
}
<div class="normal">Item 1</div>
<div class="normal">Item 2</div>
<div class="different">Item 3</div>
<div class="different">Item 4</div>
<div class="normal">Item 5</div>
<div class="normal">Item 6</div>
<div class="different">Item 7</div>
<div class="different">Item 8</div>
like image 52
Terry Avatar answered Sep 20 '22 16:09

Terry