Know Your Css Selectors

After you’ve shortened your css, it’s time to get to know your css selectors. The following selectors are all in the css2.1 specifications and should work in all modern browsers (in case you’re wondering, Internet Explorer 6 is not a modern browser!). I haven’t covered the class and id selectors as I assume you’re already familiar with them.

When using css selectors, try to think of the elements in your html document as a family tree. For example, take the following html:

1
2
3
4
5
6
7
8
9
<div id="parent">
    <h2 class="child">Child 1</h2>
    <h3 class="child">Child 2</h3>
    <p class="child">Child 3</p>
    <div class="child">
        <p class="grandchild">Grandchild 1</p>
        <p class="grandchild">Grandchild 2</p>
    </div>
</div>

The Descendant Selector

Perhaps the most commonly used selector (probably because it’s the easiest to understand) is the descendant selector.

1
2
3
div#parent p {
    margin-top:20px;
}

This will select all paragraphs that are inside the #parent div(children, grandchildren, great-granchildren etc) and give them a top margin of 20px

The Child Selector

1
2
3
div#parent > p {
    margin-top:20px;
}

This will only select paragraphs that are children of the #parent div. Granchildren, great-grandchildren etc will not be targetted by this rule.

The Adjacent Sibling Selector

1
2
3
div#parent h3 + p {
    margin-top:20px;
}

This selects the next sibling in the document tree. In our example, this means the next paragraph after the h3 that is a child of the #parent div.

Simple Attribute Selector

1
2
3
p[class] {
    margin-top:20px;
}

This will target any paragraph that has a class attribute, no matter what the class value is.

Exact Attribute Selector

1
2
3
a[rel="lightbox"] {
    text-decoration:none;
}

This selects any link on the page with a rel attribute of ‘lightbox’ and removes the underline.

There are also Partial Attribute Selectors and the Language Attribute Selector but I’ve never had cause to use them so have omitted them from this post (if you use them yourself, I’d love to hear about it!).

The downside to these selectors is that Internet Explorer 6 only understands the descendant selector and ignores the rest. Perhaps you could use them to enhance the experience of your other users instead?

Feed IconFollow me on Twitter





2 Responses to “Know Your Css Selectors”

  1. Thanks again oh mighty one…this is great. CMD + D (Bookmarked)

  2. [...] ‘rel’ attribute with a value of ‘pdf’. We can then target that link with an exact attribute selector. Combined with the :before pseudo-element, the css would look like this: a { [...]

Leave a Comment







XHTML: You can use the following tags in your comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">