Return To CS 100 Home

Advanced Stylesheets: Class and Id Selectors

Video Summary


Sometimes, you want to make certain tags or groups of tags behave differently than the rest. For example, you might like to make some text stand out, or have a different background colour on one page, but you don't want to make multiple stylesheets. You can accomplish both of these using class and id selectors. In order to use them, you will need to make changes to both the HTML and CSS files.

  1. Class selector
  2. Id selector
  3. Lab exercise


Class Selector

A "class" is a group of tags that behave differently. A common style choice websites make is alternating the colour of table rows to make them easier to follow. They accomplish this by making either the even or odd rows a different class of tr tag with a different background colour. To do this, you name the tag then put .classname behind it, where the classname could be almost anything except a few reserved words. From there, it follows the same format as anything else on a stylesheet.

This would look like this on the stylesheet:

tr.even{
background-color:lightgrey;
}

This will create a class of tr tags with the name even. Right now, this will do nothing - you'll have to tell the HTML tags you want using it to look for that class. To do this, add the class attribute to the HTML tags, in this case the tr tags, that you want using that class in the form class="classname", where classname needs to match exactly what you placed after the dot on the CSS file. It would look something like this:

 <tr class="even" >

ID Selector

An "id" is used to make one specific thing stand out on a page. IDs are meant to be unique, so if you want to change multiple things, you should use a class.

IDs can be used to change anything, so they aren't associated with any particular tag. When you are declaring one on your stylesheet, you just use the format "#idname". An example could be:

#myid{
color:purple;
}

Then, just like the class selector, you would need to tell which part of the HTML page is supposed to use that ID. If you wanted to make a paragraph have purple font colour, it would look like this:

 <p id="myid" >

Lab Exercise

Last week, we made two files, one named testing.html, which should have a table on it, and one named testing.css, which should be affecting the testing.html page

  1. On the testing.html page, add class="even" to a <tr> tag and id="myid" to a paragraph tag as shown above
  2. On the testing.css page, add the new rules for the class and id selectors as shown above
  3. Check the file to make sure they work. They could look something like this: