/ development

CSS nth-child goodness

Whilst working on a client site at work recently I came across an interesting design / CSS challenge.

Basically, the information on the page is represented by a series of boxes, let's imagine they're numbered 1 to 16. Every other row, the flow will be right-to-left, creating a sort of 'reverse S' layout (see the diagram below, and sorry for the terrible design skills!
Visual respresentation of reverse 's' layout

If this was a fixed number of items, or even a fixed number of columns, this wouldn't be so difficult. Of course, we live in the modern world, the future web world, so has got to be scalable and responsive (mobile-first, naturally). Oh, and I know "just use jQuery and add a class" is an option, but not for me as I knew it should be possible in CSS.

Knowing that nth-child was a starting point (and knowing all the browsers we needed to support also supported that!) I started off by looking at the awesome article that Heydon Pickering wrote a few months back: Quantity Queries for CSS. This got me halfway there, and although slightly off-track I'd read it if you haven't already as it's brilliant.

Using nth-child(4n+1) would get me the 5th, 9th, 12th, etc elements which was not quite there. By using nth-child(8n+1) gets closer, but also matched the first element in the row. Settling on nth-child(8n+5) gave me what I wanted - the 5th, and 12th items. (An aside: this tool by Chris Coyier is very useful for testing nth-child patterns).

From there it's just a case of adding one for each element after that you want to me. For brevity I just added one layout, but the principle would apply e.g. for 3-columns. I ended up with this:

.item:nth-child(8n+5),
.item:nth-child(8n+6),
.item:nth-child(8n+7),
.item:nth-child(8n+8) {
    float: right;
    // Other fancy styling
}

For a different number of columns, you can work it out like this:

:nth-child(Xn+y)

Where X is the number of columns * 2 (for 3 cols, this would be 6), and Y is number of columns + 1 (so for 3 cols it's 5)

And there you have it! I created a little CodePen for the finished solution; it's a bit messy but you should hopefully get the idea..

DISCLOSURE: I work for Zoocha, so credit where credit's due as this was done on their time :)

CSS nth-child goodness
Share this