Class vs ID Selector in CSS and Their Precedence
Both class and ID selectors are used to target elements in CSS, but they differ in usage, specificity, and how often they should be used. The ID selector has higher specificity than the class selector and therefore takes precedence when both apply to the same element.
Begins with a dot (e.g., .button).
Can be applied to multiple elements on a page.
Ideal for reusable styling across many elements.
Specificity score: 0-0-1
Begins with a hash (#) symbol (e.g., #header).
Must be unique and applied to only one element per page.
Best for targeting a specific unique element.
Specificity score: 0-1-0
Because an ID selector has a higher specificity score than a class selector, it will override class styles when both are applied to the same element unless a class selector uses !important.