Class selectors
- With the class selector you can define different styles for the same type of HTML element.
- Syntax
- .name {property: value;}
- selector.name {property: value;}
- Only one class attribute can be specified per HTML element
- Classes may be used multiple times on an HTML page
- A given class attribute may take one or more classes
- Examples:
CSS Code:
p.first{ color: blue; }
p.second{ color: red; }HTML Code:
<html>
<body>
<p>This is a normal paragraph.
</p>
<p class="first">This is a paragraph that uses the p.first CSS code!
</p>
<p class="second">This is a paragraph that uses the p.second CSS code!
</p>
...Display:
This is a normal paragraph.
This is a paragraph that uses the p.first CSS code!
This is a paragraph that uses the p.second CSS code!
id Selectors
- CSS IDs are similar to classes in that they define a special case for an element. In other words, they assign an identifier.
- The W3C defines class ID as "a unique identifier to an element".
- CSS IDs are similar to classes in that they define a special case for an element. In other words, they assign an identifier.
- Syntax
- #name {property: value;}
- selector#name {property: value;}
- IDs are unique identifiers and may only be used once per page.
- Use ID selectors for CSS layout.
- Examples:
CSS Code:
p#exampleID1 { background-color: yellow; }
p#exampleID2 { text-transform: uppercase; }
HTML Code:
<p id="exampleID1">This paragraph has an ID name of "exampleID1" and has a white CSS defined background</p>
<p id="exampleID2">This paragraph has an ID name of "exampleID2" and has had its text transformed to uppercase letters. </p>Display:
This paragraph has an ID name of "exampleID1" and has a yellow CSS defined background.
This paragraph has an ID name of "exampleID2" and has had its text transformed to uppercase letters.
Classes vs. IDs
- ID = A person's Identification (ID) is unique to one person.
- Class = There are many people in a class.
Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.
A note about case
CSS is not case sensitive, but XHTML is because XML is. It is best to maintain case between the (X)HTML and CSS.