Basic Selectors

Once you understand how selectors work you should find it easy to get up to speed with any of the complex CSS selectors that have great support in browsers at this point. We’ll start with some of the simplest selectors, ones you’ll be familiar with if you have written any CSS at all. Element, class and ID selectors.

The CSS Layout Workshop: Basic Selectors

Element Selectors

The most basic of the selectors is an element selector. For example, paragraphs in an HTML document are represented by the p element and wrapped in <p></p> tags. To select all paragraphs in a document we would use the following selector.

p { }

To select all level 1 headings we would use the h1 selector.

h1 { }

Element selectors will apply CSS to every instance of that element in your document.

Class Selectors

An element selector is just fine if you want all of your headings or paragraphs in a document to have the style. What if instead you want some items to differ from the main style? Here you could use a class selector.

In HTML we add a class to an element, like this:

<p class="box">Content here</p>

In our CSS we can use the class selector, it starts with a . character.

.box { }

You might sometimes see the class added to the element in the CSS, like this:

p.box { }

This will work, but I would suggest you avoid doing this as you might not always want the styles set up for .box to be used on a paragraph element. By creating the rules for .box without being specific about .box being a paragraph we could reuse this rule for any element, not just paragraphs.

<p class="box">Content here</p>
<div class="box">Content here</div>

You can add your class to multiple items in one HTML document, and the selector will select all of them and apply the same styles to each.

ID Selectors

Another way to pick out one element is to give it an ID in the markup.

<p id="box">Content here</p>

In the CSS we select an ID using the # character.

#box { }

An ID can only be used once per document, therefore would not be an ideal choice for our class of .box which we might want to reuse on several elements. An ID also gives the element higher specificity, which can make it difficult to overwrite the styles later. Therefore in the interest of creating reusable CSS, I would suggest avoiding styling based on an ID. If your element has an ID applied for other reasons, you can still add a class and apply your CSS via the class selector.

Next lesson: Combinators