CSS Selectors

When we want to add styles to parts of our HTML document, we use selectors. These describe what part of the document we want to style.

To select all elements with the same tag, we just use the tag name. Here are some examples:

  • h1 - selects all h1 elements
  • body - selects the body element (there should only be one)
  • p - selects all p elements

Sometimes we want to select only a subset of our elements. We can add the class attribute to HTML tags, like this:

<div class="notice">This is an important notice.</div>

When we use the class attribute, we can select all elements on the page with that particular class by putting a period in front of the class name. Here are some examples:

  • .notice - select all elements with the class notice
  • .sidebar - select all elements with the class sidebar
  • .pull-quote - select all elements with the class pull-quote

Note that class names should start with a letter and be made up of letters, numbers, dashes, or underscores. No spaces or other characters should be used.

We can combine these selectors. If you list two selectors with a space in between them, this narrows the list of elements that can be found. The first selector is used to determine what elements to look in and the second is used to select elements within those. Here are some examples:

  • .sidebar a - select all a elements within elements with the class sidebar
  • ul li - select all li elements within ul elements
  • p .highlight - select all elements with the class highlight within p elements

If you list two selectors with a comma between them, this selects elements that match either selector.

  • h1, h2 - selects all h1 and h2 elements
  • .notice, .warning - selects all elements with either the class notice or warning
  • ul .selected, ol .selected - select all elements with the class selected within ul or ol elements

There are a lot more ways to use selectors. You'll get some practice on the next page.