nth-child CSS Selectors For 4 Column Grid Layouts
Here’s how to select every element of either the 1st column, the 2nd column, the 3rd column, or the 4th column, of a 4-column grid layout. In other words, these are CSS selectors for every fourth element.
The column/grid elements must have a CSS class assigned to them. In this example, the class is “grid_3”.
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 to target each of the 4 columns:
Column 1 (will apply to element number 1, 5, 9, etc.): :nth-child(4n-3)
Column 2 (will apply to element number 2, 6, 10, etc.): :nth-child(4n+2)
Column 3 (will apply to element number 3, 7, 11, etc.): :nth-child(4n+3)
Column 4 (will apply to element number 4, 8, 12, etc.): :nth-child(4n+4)
Example Usage
/* First column. */ #wrapper .grid_3:nth-child(4n-3){ padding-left: 0; } /* Second column */ #wrapper .grid_3:nth-child(4n+2){ padding-left: 2%; padding-right: 2%; } /* Third column */ #wrapper .grid_3:nth-child(4n+3) { padding-left: 2%; padding-right: 2%; } /* Fourth column */ #wrapper .grid_3:nth-child(4n+4){ padding-right: 0; }
See more: :nth-child, columns
Questions and Comments are Welcome