When to Use Class and ID Selectors
May 14th, 2007 Noor
Use class selectors when you need to apply a style multiple times within a document and ID selectors for one-time only appearances of a style within a document.
In the following style sheet, #banner, #sub_banner, #nav1, #nav2, #footer, and #content are ID selectors and .title and .content are class selectors.
Apply the ID and class selectors into the HTML code:
The ID selectors identify unique attributes that have one instance in the document tree, whereas class selectors can be used frequently throughout the web page. Remember that ID selectors use a hash, “#“, while class selectors begin with a period, “.“.
Typically, web developers will use ID selectors to mark off unique sections of a web page. In the previously shown solution, notice that the page is divided into the following sections:
>header
>content
>navigation
>blipverts
>siteinfo
By assigning these sections their own ID selector, designers are able to apply customized styles to those areas of the page, while keeping those same styles away from the other sections. This is accomplished through the combination of descendent selectors with ID selectors.
In the following example, the different H3 elements get different CSS rules:
Posted in CSS | No Comments »
