ID Selector

In the previous tutorial, we looked at a few different types of CSS Selectors and we used the class selector to apply a style to all elements that used that class name. In this tutorial, we will look at the ID selector.

The ID selector is used when we want to apply a style to a single element. An ID is unique for each element. We can use a class for multiple elements but we should only ever use an ID for a single element. If we use the same ID for multiple elements, problems will start to occur especially when using JavaScript code.

An HTML element can be given an ID like in the example HTML code below:

<p id="blue">This text is blue</p>

The ID style is specified in the CSS code and a hashtag (#) is placed before the ID name.


Watch the video below to see how you can use IDs in your HTML and CSS. Then scroll down to see the sample code.

Here is the sample HTML code (it references a CSS file called stylesheet6.css in the resources directory):

<!DOCTYPE html>
 <meta charset="utf-8"/>
 <link rel="stylesheet" href="resources/stylesheet6.css" type="text/css"/>
 <p id="blue">This is a blue paragraph</p>
 <p id="green">This is a green paragraph</p>
 <p id="red">This is a red paragraph</p>

And here is the sample CSS code:


We will be looking at more selectors in upcoming tutorials. Happy coding!