Note: Occasionally, this blog will delve into advanced development topics that may be a little advanced to the non-technical readers. They usually are still understandable to the layman, but might not be as interesting. You’ve been warned!

CSS selectors are one of the most basic parts of CSS – it is the labels that you apply to HTML elements to style them. Everyone knows the standard id and class, but WordPress sometimes leads to situations where you don’t have nice clean selectors like that. If you have a plugin or theme that doesn’t add unique selectors, or worse still, uses dynamic selectors that constantly change, it can be very hard to target specific elements. Notably, ul and li elements can be problematic: you often want to apply custom styling to the first and last elements, such as removing a leading or trailing border.

How do you do this without hacking up the theme, resorting to JS, or any other unsightly hacks? Well, it turns out there’s a few CSS selectors for that. At our disposal is:

  • nth-child(n)
  • nth-last-child(n)
  • nth-of-type(n)
  • nth-last-of-type(n)
  • first-child
  • last-child
  • only-child
  • first-of-type
  • only-of-type

So each one works slightly differently, but when paired with

  • elements, allows for a lot of flexibility. You’ll notice that they seem to be in pairs, with the general pattern being that the first selector helps to target from the beginning, while the second starts at the end. For example:

    li:nth-child(3) {CSS Styling}

    Will target the 3rd item in the list, while

    li:nth-last-child(2) {CSS Styling}

    will select the second to last element. The first and last child selectors are basically the equivalent of using 1 for the nth-child selectors, and are very helpful for those removing leading and trailing borders. The selectors using type are used for the actual element instead of the child – for example, you would use them if you were trying to style the 3rd ul on a page, instead of the third li withing one of the ul. Finally, the only-child selector is incredibly helpful when styling code that may have a variable number of elements returned – such as a blog archive page, or a widget that is getting recent posts. The styling will be automatically removed if there are multiple elements, so you can make the styling ‘responsive’, expanding to fill an area if it’s the only result.

    For a whole lot more on CSS selectors, and more in depth explanations of the ones I listed, check out The 30 CSS Selectors You Should Memorize