Working with the id element

Web Design with HTML & CSS

🕑 This lesson will take about 10 minutes

In the previous lesson, we looked at a few different types of CSS Selectors and we used the HTML class element and the CSS class selector to apply a style to all elements in a web page/site that used that class name. In this lesson, 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. For example, we may want to fetch the data entered by a user into a specific textbox in a form on a web page. We can use an ID to refer to specific data that we want eg. username, email, password. If more than one text box had the same ID, we would have problems accessing the data we want.

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

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

The style that will be applied to elements that have the id is specified in the CSS code. A hashtag (#) is used at the start of the id name to indicate that you are referring to an id.

#blue{
       color:blue;
       font-family: Arial;
}

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 theme.css):