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.

#blue{
       color:blue;
}

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>
<html>
<head>
 <title>IDs</title>
 <meta charset="utf-8"/>
 <link rel="stylesheet" href="resources/stylesheet6.css" type="text/css"/>
</head>
 
<body>
 <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>
</body>
 
</html>

And here is the sample CSS code:

#blue{
 color:blue;
}
 
#green{
 color:green;
}
 
#red{
 color:red;
}

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