Id Selectors
An ID selector matches an element with a given id attribute. It has greater specificity than class selectors, but earlier cascade stages can still determine which declaration wins.
Target a unique element and compare specificity only after earlier cascade stages.
The "Visit us" section needs a soft green background, and it is the only one of its kind. It already has id="visit" so the nav can link to it. You can select it through that id, but ids carry a weight in the cascade that deserves respect.
The rule
A hash means id:
#namepicks one element, with heavy weight.
#visit {
background-color: honeydew;
}Every example uses the Harbour Café page from the first lesson of the course: a header with an h1 and a nav of two links, a section#menu holding an h2 and two article.dish cards (the second is also .special), each with an h3, a p.price and a description p, then a section#visit with an h2 and one p, and a footer with one p.
#visit matches the single element whose id is visit. Ids are case-sensitive and must be unique on the page, so an id selector points at one element at most.
The weight is the important part. An id scores (1,0,0). Specificity is compared column by column from the left, so one id outranks any number of classes. #menu p (1,0,1) beats .dish.special .price (0,3,0).
That power is exactly why many teams avoid ids in stylesheets:
- To override an id-based rule later, you need another id or
!important, and the weights keep escalating. - An id cannot be reused, so the style cannot be reused either.
The common approach: keep ids for what needs a unique name, such as in-page links (href="#visit"), form labels and scripts, and style with classes. If you must reach an element that only has an id, [id="visit"] selects it with class-level weight (0,1,0).