Alice's EDA Blog



".pikachu I choose you!"

Using classes and IDs in your CSS

February 2019

When working with CSS you use a selector to identify which HTML elements you want to style. For instance, if you wanted to style every <p> element you would use:

p {
  /* All your fav CSS rules here */
  }

In this case p is your selector. But element types aren't your only option when it comes to selectors – you can make your own using classes and IDs!

Classes and IDs

The way you use classes and IDs is very similar. To give an HTML element a class, add class="class-name" to that element. For example:

<div class="wonderfully-descriptive-class-name"></div>

To give an HTML element an ID, add id="id-name" to that element. For example:

<div id="very-excellent-id-name"></div>

When you've given an element a class or ID you can create style rules that apply specifically to elements with that class or ID. Note that to specify your selector is a class you will need to use a . at the beginning of the class name and to specify an ID use a # at the beginning of the ID name. For example:

.class-name {
  /* Many wonderful CSS rules */
  }
      
#id-name {
  /* Maybe just one CSS rule in here, but it's a really good one */
  }
But which should I use?

Use a class when you want to apply that style multiple times on your page. You can reuse one class on multiple elements, and elements can have multiple classes applied to them.

Use an ID when you're styling one specific element. There should only be one element on your page using each ID.