The ID Selector
The id selector uses the id attribute of an HTML element to select a specific element.
An id should be unique within a page, so the id selector is used if you want to select a single, unique element.To select an element with a specific id, write a hash character, followed by the id of the element (#para).
The Class Selector
The class selector selects elements with a specific class attribute. To select elements with a specific class, write a period character, followed by the name of the class (.center)
Classes and IDs
At first glance, classes and IDs appear to function identically, but there are important differences between the two:
- IDs can be applied to one and only one element in a web document.
- Classes can be applied to an unlimited number of elements, even different types of elements on the same page.
- If conflicting styles from an ID and class are applied to the same element, the ID will outrank the class in the cascade.
Example: Class and ID, Same Element
Both an ID and a class may be applied to a specific element:
An ID is restricted for use with a single element in a web document. Using the same ID more than once on a page will result in an error. We’ll use IDs sparingly in this course, preferring classes for their greater flexibility.
Naming Classes and IDs
We should maintain the goal of keeping our content and presentation as separate as possible. Using class and ID names that describe how the element appears departs from this objective. We should try to use class names that describe the meaning of the content, not its appearance:
|Problematic names||Better names|