Lesson Overview

In the previous lesson on CSS Syntax, you learned about basic element selectors (which are also called type selectors). There are other types of selectors you can use if you want to do more than select all elements of a certain type. ID selectors allow you to select and style one specific item in a document by a unique ID. Note that you should use ID selectors sparingly, as they're not as re-usable and modular as other kinds of selectors.


Make sure that you've worked through the previous tutorial, CSS Syntax before proceeding through this lesson.

ID Selectors

ID selectors can be used when you want to style only a single element in a page. For example, you might want to style all paragraphs with a certain font styling, and one particular paragraph with a yellow background.

An ID selector uses a CSS Identifier. CSS Identifiers are assigned to an element using the id="" attribute in the element's opening tag. CSS Identifers are used for more than just CSS (i.e. JavaScript) and they always follow the same naming conventions: CSS Identifiers must be in lower-case letters only, and should use a hypen to separate words in the identifier. Examples of correct, standard CSS Identifiers include page-heading, background-color, highlight, and dfn-css-id. Later, you'll notice that CSS properties also follow this standard.

ID selectors in your CSS code start with a # sign. Note that you don't use the # sign in the id="" value, only inside your CSS code when you're defining a CSS rule using an ID selector. For example, if you have some HTML code defined as:

<aside id="note">...</aside>

You can create a CSS rule using an ID selector for the element with id="note":

#note {
  background-color: yellow;
  color: navy;

ID selectors are used when you want to style only one specific item on the page. You need to include the id="" attribute on the HTML element you want to style. The example above looks for an HTML element with an id attribute value of "note". Since an id="" value must be unique, this will select and style exactly one element, regardless of the element name/type.

In this case, this rule will style our <aside id="note"> that we defined earlier. This element will be styled according to the styles defined in the #note rule (yellow background and navy text).

Here's a CodePen.IO example that uses an ID selector to style one of the <strong> elements in the page.

See the Pen CSS Selectors: ID by Wendi Jollymore (@ProfWendi) on CodePen.

(direct link to the id selectors demo CodePen, opens in the pen tab)