id Selector

The id attribute is used similarly to class, but it is used for targeting a single element rather than a group. id must be used to name an element uniquely (in other words, two elements can’t have the same id name in the same document). It is not a problem for an id value to be used in multiple documents across a site; it only needs to be unique within each document. If you have several elements that need a similar treatment, use class instead.

The following example gives a paragraph a specific ID (note that the value of an id attribute must always begin with a letter):

    <p id="j042801">New item added today</p>

ID selectors are indicated by the octothorpe (#) symbol within the style sheet as follows:

    p#j061998 {color: red;}

The element name may be omitted:

    #j061998 {color: red;}

In modern web design, id attributes are frequently used to identify main sections (usually divs) within a page. Some common id values for this purpose are content, header, sidebar, navigation, and footer. Establishing sections of the page makes it easier to create contextual selectors so that elements can be styled based on where they appear on the page without the need to create extra classes.

Like class attributes, id names should be chosen based on the semantic role of the element, not its presentation. For example, for a sidebar on the left side of the page that contains news, it is preferable to name the div id="sidebar-news" rather than id="sidebar-left".

Tip

The id attribute is also used in scripting ...

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.