Getting the last item in an odd-numbered list

In a responsive web page design I was concocting today, I realized a problem with this approach:

.subgroup {
  width: 50%;
  float: left;
}
.subgroup:nth-child(odd) {
  clear: left;
}

The idea was to arrange several blocks of text into two columns, clearing the float for every other block to force a new row. However, this was rather unattractive when I had an odd-numbered collection of blocks — especially when there was only one block, and therefore no indicator of why it only covered half the smartphone’s already-narrow screen width.

I knew I could solve the problem using jQuery; I wanted to solve it using pure CSS. After giving it some thought, I finally realized I could add this:

/* last item in an odd-numbered list */
.subgroup:last-child:nth-child(odd) { 
  width: 100%; 
}

Problem solved! The last item will now be stretched to 100% of the width only if it is also an odd-numbered element.

A List Apart has a few more stupid CSS tricks using “nth-child”.

Leave a Reply

Your email address will not be published. Required fields are marked *

*