IDs and Classes - Chapter 3

➜ Chapter Booklet HERE

IDs and Classes

There are two other important ways to select content in an HTML file which will be styled using CSS rules. They are IDs and classes.

IDs and classes are ways to identify HTML elements, within an HTML file, that can then be referenced within a separate CSS file or within the <style> element in the HTML file.

They allow for a great deal of flexibility because IDs and classes can be applied to any element, and as such, they are global attributes. They are similar to other identifiers you might see used in programming languages, in that you can name them whatever you like and refer to them in other areas of your code.

For example..

In the HTML file:

<h1 id=“fun”> Content goes here </h1>

In your CSS file:

#fun {
color: white;

}

To use an ID you would include it in the opening tag of an element in the HTML file, as an attribute, then you would use it as the selector in your CSS rule. To name an ID you should not use spaces and it is customary to begin with a letter. Camel case is also often employed.

If I wanted to name my ID something that contained two words I could write:

id=“funStyle”

As long as I don’t have any spaces I could also write: 

id=“fun_Styles_1”

So id is the attribute and “fun_Styles_1” is the value assigned to it. There can only be one id value/name per HTML document...you can only use the id’s name once in an HTML document.

By contrast, you can use the name of a class as many times as you want in the same HTML file. This means you can apply the same style to different elements, by using classes.

In the HTML file:

<p class=“redStyles”> content goes here </p>

In the CSS file:

.redStyles {

color: white;

}

So IDs and classes serve as selectors in CSS rules. You use the ID selector by prefacing it with a # and you preface a class with a . in a CSS rule.

I could apply the “redStyles” class to many HTML elements in my HTML file:

In the HTML file:

<p class=“redStyles”> content goes here </p>

<h1 class=“redStyles”> content goes here </h1>

<h2 class=“redStyles”> content goes here </h2>

Etc.

If I wanted to make all of the content in those various elements the color red, I would only have to use the class name once in my CSS file to do so.

.redStyles {

color: red;

}

This would change all of the text in the above elements to red, with just one CSS rule. So class names can be used multiple times in the same HTML file, but specific ID names can only be used once (you can have more than one ID in a file, but you can’t use a particular name/value more than once).

Let’s see how this works in our own documents and add in an ID and classes into our HTML file.

Danita Smith