CSS Refresher: Selectors You May Have Forgotten

While working through a code rework on an old site last week, I remembered a few CSS tricks I hadn’t had to use for a while. I thought I’d post a little refresher to share these tips that might help you out of a coding bind.

The child selector:

Let’s say you have an unordered list with an id of ‘nav’ and you only want a certain style on the top level list items. If you try to target them by using #nav li, all of the the list items, even in nested lists in that ul will be targeted. This is the perfect place for a child selector. If you use #nav > li, only the direct children (list items one level down) will be affected.

The adjacent sibling selector:

I’ve pulled this one out of the hat more than a few times lately. This rule targets an element that directly follows another element. For example, let’s say you want the first paragraph after every subheading to have a black background with white text. If your subheadings are H3 tags, the rule would look like this:

H3 + p { background-color:#000;color:#fff; }

The attribute selector:

This one is less well known, but very useful if you’re trying to target markup that you don’t have access to. I used this recently working with jQuery to style code in a third-party iframe. The anchor tags had no classes or IDs, so I used the ‘rel’ attribute to style the anchor in question.

Let’s say you’re trying to style an anchor tag with the attribute rel=”gallery1.” You could use this rule:

a[rel=gallery1] { text-decoration:underline; }

This would also be useful for styling external links with the attribute rel=’external.’

Using Regular Expressions

The attribute selector can also be used in combination with regular expressions to match a part of your code. For example, you might have links to PDFs on your site that you want to display differently, maybe adding a PDF icon after the link. Rather than add a class to all those links, you could target them with an attribute selector and regular expression as follows: