ID Selector in CSS
- W3C defines ID as “Unique Identifier to an Element“.
- In CSS we can style HTML elements using selector.
- In CSS we can define our own selectors - “id” and “class“.
- ID selector is used to style unique elements or Single Element.
- ID selector uses id attribute of the HTML element
- ID selector is defined with a “#” followed by rule
- ID defined once per document.
Sample Live Example
<html> <head> <style type="text/css"> #heading1 { text-align:center; color:red; font-size:26px; } </style> </head> <body> <h1 id="heading1">Sample Heading !!</h1> </body> </html>
Explanation of the Code :
We have defined following rule with ID selector
#heading1 {
text-align:center;
color:red;
font-size:26px;
}
- We can apply this style rule to the element with the id=”heading1″.
- We can have single unique id associated with HTML element that’s why this selector comes into existence and we can use “ID selector” to style only single or unique html element
Precaution : Using ID Selector
[attention]- Do NOT start an ID name with a number! It will not work in Mozilla/Firefox.
- You should use ID names that only include letters, numbers, hyphens and underscores for compatibility with the older browsers