Welcome, guest! Login or Register

Using CSS class and ID selectors

Tutorial by anne, last edited on January 4th, 2008

This is a simple tutorial teaching you how to use class and ID selectors in CSS.

The difference in Class and ID

A class is a style that can be duplicated on the page multiple times. For instance if you want every div tag with the class "greenbox" to have a green background with a black border, you would write it like this:

<div class="greenbox">
</div>

If you wanted to make more than one of these boxes on the page it would need to be a class.

But suppose you only want it to show up on the page once?
Then you would make it an id, which would look like this:

<div id="greenbox">
</div>

Selecting IDs and Classes with CSS

To select a class in your CSS you use a dot before the class name. So following the previous example, the CSS would go something like this (entering your values):

.greenbox { background: green; border: 2px solid #000; }

To select an ID, you use the pound sign (#). Again, following the previous example, the CSS would look like this:

#greenbox { background: green; border: 2px solid #000; }

And that's pretty much it! Happy coding :)


This tutorial was written on January 4th, 2008 by anne. You can leave a comment below to help keep track of errors. Follow comments to this posting through the RSS feed.

Comments:

ziggybob said:
Jan 04, 09:59:38 PM

Be careful not to start your class or id names with a number- you can include a number after or with the letters but it canNOT start with a number.

Good: .selector1
Bad: .1selector

Leave a comment:

Your name:

Your email:

Your comment: