and IDs

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: Multiple Classes, One Element Type
Let’s look at our earlier example again, but this time let’s create three CSS classes to style the three paragraphs differently:

Example: One Class, Multiple Element Types
A single CSS class may also be applied to different element types on the same page:

Example: Multiple Classes, One Element
Multiple classes may also be applied to a specific element:

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.

The <span> Element
Sometimes we don’t want a style to apply to an entire text element, but just a specific subset of text.  For these instances, we use the handy <span> element:

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
.green .slogan
.underline  .booktitle
.center  .caption
.bigletters  .headline


CSS Selector Reference