Classes and IDs
In CSS, you can have an element inherit a style based on the element's id, class, or element type. This allows you control over all of the elements on a page, a group of elements, or just one element. In all of the tutorials so far we have mostly dealt with controlling all of the same elements on a site. With ids and classes, we can control either individual elements or groups of elements.
IDs
Ids allow you to control a single of element. This element inherits the style that you apply to the id. To declare a id in a style sheet you have to use the pound (#) symbol followed by the id name. You can also add the element that you want to use before the pound symbol if you want to. Here is an example of both of the syntax options.
<style>
#first {color: blue;}
p#first {color: blue;}
</style>
By using the #first syntax, we can apply the id to any element we want, where as the second syntax can only be applied to the paragraph element.
Classes
Classes are just like ids, but they control a group of elements, in other words, you can use a class more then once, where an id can only be used once. To declare a class, you have to use a period (.) then the class name. Just like the id element there are two syntax that can be used to create a class.
<style>
.first {color: blue;}
p.first {color: blue;}
</style>
Let's use a class to create a table that will alternate the background colors of each row. We will also use an id to create a table header.
<style>
th#header {color: blue;}
td.odd {background-color: #FFF4CE;}
.even {background-color: #FFE8E9;}
</style>
This is the style sheet will be using, you can see that it changes the color of the element with the id of header to blue. Also there is the odd class for the td element that will change the background color to the hex value of #FFF4CE. The last part of our style has an even class that changes the background to #FFE8E9. Now it is time for our HTML code.
<table> <tr> <th id="header">A table to demonstrate classes and ids.<th> </tr> <tr> <td class="odd">This is a cell with the class set to odd.</td> </tr> <tr> <td class="even">This is a cell with the class set to even.</td> </tr> </table>
Once the style is applied to our HTML code the output will look like the table below.
| A table to demonstrate classes and ids. | |
|---|---|
| This is a cell with the class set to odd. | |
| This is a cell with the class set to even. |
iEntry 10th Anniversary
CSS Snippets
JavaScript Snippets