Home Page
ID & Class
Elements of CSS
Sample
Bibliography
Box Model
Toby's Studio

ID & Class in CSS

Class first

Without CSS, most of us got in the habit of formatting text using tons of font, formatting, tables and, when all else failed, transparent .gif files to use as spacers. It was the only way to get our pages to look as we wanted them to.

CSS1 changes all that. We now have the tools to format a class in css and be able to use exactly the same formatting properties any time we wish. When we want to change how things look, change the class once and away we go.

Let's take a simple example.  Suppose you don't like to run text up against the edges of your borders, so you use something like <blockquote> to add space.  Then you frequently quote material and you want it indented even further -- more <blockquotes>, plus you need to put the quoted material in italics -- all those <i> tags.  To use css for this, you would add to the header (or reference a separate css file)

<style> 
    p {      text-indent: 3em; }
    p.quote {text-indent: 6em; 
              font-style: italic; }
</style>

In your html, you'd simply mark your text like:

<p>Your main text you want to look normal. Notice that this style is different from the rest of the page. I use text-indent for the first line of my paragraphs, but for the purposes of this example, I have overridden it.</p>

<p class="quote">Your italic, text, which I have formatted using the above tag in my css so you can see how it works.</p>

Using ID's

ID's work about the same as classes, but there can only be one use of an ID per page. What is the advantage of using it just once? Create an ID of "menu", stick all your menu items in it (as I have done with the menu items on the left) and they will be exactly the same on every page in your site -- but you only want one menu per page.

Because you only reference an ID once, you can then put all kinds of contextual selectors on it without worrying that something elsewhere will go wonky.

Be careful how you name your classes and ID's. Don't use any html or css terms or your code may have unexpected results. Use descriptive names whenever possible.

© 2003 by Toby Scott
Validate