A Complete Guide to Web Design

(やまだぃちぅ) #1
Selectors 397

CSS

Selectors

Web Design in a Nutshell, eMatter Edition

CLASS and ID Attribute Selectors


Attribute selectors allow web page authors to apply style rules based on special
identifying attributes placed within HTML element tags. There are currently two
available attribute selectors: CLASS and ID.


CLASS selector


You can classify elements by adding aCLASSattribute to the HTML element tag.
Elements in a class can then be modified with a single style rule. For instance, you
can identify all the items in the HTML document that you classify as “important”:


<H1 CLASS="important">Attention!</H1>
<P CLASS="important">Your account is past due.</P>

To specify the styles for elements of a particular class, add the class name to the
HTML selector, separated by a period (.). Note:CLASSnames cannot contain
spaces; use hyphens or underscores instead if necessary.


H1.important { color: red }
P.important { color: red }

To apply a property to all the elements of the same class, omit the tag name in the
selector (be sure to leave the period—it is the character that indicates a class):


.important { color: red }

ID selector


TheIDattribute is used similarly to CLASS, however, it is used for targeting
specific elements rather than classifying them. If you have several elements that
need treatment, useCLASS. If you have a specific element that must be uniquely
treated, you can give it anID:


<P ID="061998">New item added today</P>

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


P#061998 { color: red }

Omit the HTML tag name to apply properties to all elements with a given ID:


#061998 { color: red }

Pseudo-Selectors


The CSS1 Specification provides several pseudo-elements and pseudo-classes that
are not based on structural elements of a document. They can be used as selec-
tors, but the code does not appear in the HTML source, rather, they are interpreted
by the browser based on context and function. Pseudo-selectors are indicated by
the colon (:) character. Unfortunately, as of this writing, 4.0-version browsers do
not support pseudo-selectors.


Pseudo-elements


In CSS1, the pseudo-elements (sub-parts of existing elements) arefirst-line
andfirst-letter. They can be used to apply styles to the first line or letter of

Free download pdf