For example, if you have to change the text color of all <p> elements then element selector can be utilized. However when you have to target a single <p> tag then a more specific selector will be required such as an id selector.
Syntax
The id selector is described with the # sign followed by the element’s id.
Rules to implement id selector
There are some rules to follow to deal with id selectors.
The first rule to follow while dealing with id selector is that it must have at least one character and it can’t start with a number. For example:
Within the same page, multiple HTML elements can’t have the same id:
If an element has an id then it must be unique:
The final rule is that the id name and property value must be the same:
Now consider the following example with the id “style”:
In the above snippet, one of the <p> elements is styled according to the id “style”. Therefore the properties of #style will apply only on that <p> element as shown in the below output:
The id selector can be used on various HTML elements like images, paragraphs, headings, etc.
CSS Specificity
The CSS specificity is a set of rules using which the web browser determines which property is most suitable/appropriate to an element. In CSS, the id selector has the highest specificity among all other selectors due to its uniqueness.
For example, the below given code has two styles pointing to same element i.e. <p>. Now in this case what will be the output?
<head>
<style>
.style1{
background-color:brown;
color: greenyellow;
text-align: center;
}
#style {
background-color:gold;
color: black;
text-align: center;
}
</style>
<</head>
<body>
<h3> ID Selector</h3>
<p class="style1" id="style"> Welcome to Linuxhint.com </p>
<p> second paragraph</p>
</body>
</html>
As the class style is declared first and paragraph is pointing to the “class” style first so, will the browser apply the styling of class selector?
No! The browser will determine the specificity of these selectors. As the id selector has higher specificity so it will implement the properties using id selector as shown in the output:
Conclusion:
The CSS id selector used the access the id attribute to give styling to a specific HTML element. The uniqueness makes the id selector priority over other selectors. It has highest specificity compared to all other selectors. This write-up provided a detailed understanding of id selector, its syntax, some rules that must be followed while dealing with id selectors and lastly, it provided the guidance about the CSS specificity.