CSS id selectors
As specified earlier, we have to specify the selector, while we are writing the set of rules. It is one of the important things while writing CSS. One such selector is the id selector. The name clearly says that while we define the set of rules, we just mention the id of the element(with the # sign), as the selector. This is called an id selector.
Giving the id selector just means that we are mentioning the id of the element, which has been given to it, in the HTML file. Note that the id of the element has to be unique.
To style the element with an id, you just have to write a pound sign(#) and then the name of the id of the tag you want to style (as can be seen in the below example).
Remember that id is unique and hence it is supposed not to be repeated for any other element on the page. However, you can use a different id for some different elements, but avoid using the same id’s for different elements.
The below example demonstrates how you can do that –
This code can be written either in internal CSS or external CSS. Here, the id is selected using the hash sign, and the main is the name of the id(or you can say the main is the id), and within the curly brackets, there are some properties that are being applied to the element associated with that id.
Now, let’s have a look at an example, which explains the id selector –
As you can see, in the above example, we just have 2 divs, and one div is with the main id. Also, we have written the CSS (internal CSS), in which, we have specified that we want to apply the mentioned set of rules, for the element with the main id.(refer to the above example for observing how we write it).
If you have a look at the output, we can find that the div with the main id is going to be styled, and not another one. Let’s have a look at the output of the above code –
As you can see, only the element with the main id was given those styles, while both the elements are divs only. So, we can make use of the id selector, when we need to style some elements which are having some specific id. Remember that, we have to use the # sign, to mention the id of the element.