Wednesday, August 27, 2008

Class and ID Selectors

Class Selectors

To use a class selector in CSS, you must use the class attribute in your HTML. Here is an example: <p class="last_para"> . The class selector is simply the name of the class prefixed with a period (.). The class selector of the example above is .last_para . Here is a CSS rule that uses a class selector:
.last_para {background-color: gray;}
If you include an element type selector before the Class selector, then only those elements which are also in the class will be targeted.
Example: p.last_para {background-color: gray;}
The above code will only target those p elements that are in the last_para class.
In (X)HTML, the class attribute can have more than one value - that is, an element can be in more than one class. To do this, the class names are entered as a space-separated value.
Example: <div class="main first observation">
A class selector can target an element that is in more than one class - each class name is prefixed with a period and they appear one after the other with no spaces between them. Example: .first.observation {font-color:red;}
Note: the order that the class names appear in the (X)HTML class attribute value or in the CSS selector is not important.

ID Selectors

To use an ID selector in CSS, you must use the id attribute in your HTML. Here is an example: <div id="nav_bar"> . The ID selector is just the name of the ID prefixed with the pound symbol (#). The ID selector in the above example is #nav_bar . Here is a CSS rule that uses an ID selector:
#nav_bar {float:right;}
If an element type selector is followed by an ID selector, then, only the specified (X)HTML selector that has the specified ID will be targeted. But this is not really necessary because an ID has to be unique in an (X)HTML document - only one element in an (X)HTML document can have a particular ID. It is of no use for an element to have more than one ID because there cannot be more than one instance of an ID in an (X)HTML document.
Example: div#nav_bar {float:right;}
The above code targets a div that has the nav_bar ID.

Note that class and ID names are case-sensitive in both (X)HTML and CSS.

No comments: