Advanced CSS Selectors

There are so many ways to target elements using CSS that there's almost nothing you can't grab and add styling to. We've already talked about some of the basic ways like element types and classes, so here are some of the more advanced selectors we can use.

Note: This is an incomplete listing. For a full list of advanced selectors, refer to the links on the bottom.

Descendent. Elements nested inside one another. In this example, only the <strong> tags inside of an <h1>

  • CSS: h1 strong { text-decoration: underline; }
  • HTML: <h1><strong>Extra</strong> important.</h1>

Child. The difference between descendent and child is a bit confusing. Child selectors only apply to matching elements directly inside the parent, and not anywhere further down.

  • CSS: #chapter1 > p { color: navy; }

Sibling (Adjacent). Elements that appear next to each other on the same level. For example, you might want to apply a different margin to the paragraphs right after a heading.

  • CSS: h1 + p { margin-top: 0; }

Attribute. You can target elements based on whether they have a certain attribute. Not too common.

  • HTML: <img title="geckos">
  • CSS: img[title] { color: red; } (has a title attr)
  • CSS: img[title="geckos"] { color: red; } (has a title attribute that equals "geckos")

Universal. Applies to all elements regardless of their type. This selector is useful when combined with other selectors, but it's rarely written on its own. The * is implied if it's missing.

  • CSS: *.colored { color: navy; }
  • Same as .colored { color: navy; }

Pseudo. Pseudo CSS selectors describe elements that cannot be described by the document tree, usually elements that are dynamic in some way. Useful for links and forms.

  • :link - a link that hasn't been visited yet.
  • :hover :visited :active - other states that a link can have.
  • CSS: a:hover { color: red; }

The CSS Zen Garden is a really cool example of all that can be done with just CSS!