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. 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 ID style is specified in the CSS code and a hashtag (#) is placed before the ID name.

#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):

<html>
    <head>
        <title>IDs</title>
        <link rel="stylesheet" href="theme.css" type="text/css"/>
    </head>

    <body>
        <p id="bluetext">This paragraph will be blue</p>
        <p id="greentext">This paragraph will be green</p>
        <p id="redtext">This paragraph will be red</p>
    </body>
</html>

And here is the sample CSS code (theme.css file):

#bluetext{
    color: blue;
    font-family: Arial;
    font-size: 14pt;
}

#greentext{
    color: green;
    font-family: Times;
    font-size: 12pt;
}

#redtext{
    color: red;
    font-family: Verdana;
    font-size: 16pt;
}

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