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:

a[href$=".pdf"] { background:url'(images/pdf-icon.gif') no-repeat right top;padding-right:20px; }

Since ‘href’ is an attribute we can target it this way using the $= to specify any link that ends with .pdf. $= will look for the end of a string, while ^= will target the beginning.

More on attributes and regular expressions from Sitepoint: http://reference.sitepoint.com/css/css3attributeselectors

Hope these help make your coding life a little easier.

4 Comments

  1. Great tips, both new and reminders, Debbie. For someone realtively new to CSS, I appreciate this!

    • Glad it was helpful, Dennis!

  2. I love your blog Deborah, very good information!

    • Thanks, Chris! Glad it’s helpful!

Leave a comment