Software Developer

nth-child CSS Selectors For 3 Column Grid Layouts

Here’s how to select every element of either the 1st column, the 2nd column, or the 3rd column of a 3-column grid layout. In other words, these are CSS selectors to select every third element.

The column/grid elements must have a CSS class assigned to them. In this example, the class is “grid_4”.

In addition, you should have some “wrapper” around these elements. If the elements are list items (li), then the wrapper is the ul element (or “ol”). And, that wrapper should also have a CSS ID or class assigned to it. In the example below, we are using “#wrapper”. Substitute that with your own wrapper ID or class.

Here are the “nth-child” formulas for each of the 3 columns:

Column 1 (will apply to element number 1, 4, 7, etc.): :nth-child(3n-2)
Column 2 (will apply to element number 2, 5, 8, etc.): :nth-child(3n+2)
Column 3 (will apply to element number 3, 6, 9, etc.): :nth-child(3n+3)

Example Usage

/* First column. */

#wrapper .grid_4:nth-child(3n-2){
    padding-left: 0;
}
 
/* Second column */

#wrapper .grid_4:nth-child(3n+2){
    padding-left: 2%;
    padding-right: 2%;
}
 
/* Third column */

#wrapper .grid_4:nth-child(3n+3) {
     padding-right: 0;
}

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]