<< Return to Syllabus

CSS Tutorial

Step 5: Classes, Id's, <div>, and <span>

Classes and ID's

CSS seems nice so far, but what if it's not specific enough? You may want different styles for two different unordered list elements. CSS can uniquely identify them if you use class or id attributes. You can add these attributes to any HTML element and then you'll have an extra way of identifying those elements in your CSS rules. Here's an example:

The Code

<html>
   <head>
      <title> Title of my webpage </title>

   <style type="text/css">
      p.bright { color: #7777ff; }
      p#dark { color: #111144; }
</style> </head> <body> <p class="bright"> My first paragraph. My first paragraph. My first paragraph. </p> <p class="bright"> My second paragraph. My second paragraph. My second paragraph. </p> <p id="dark"> My third paragraph. My third paragraph. My third paragraph. </p> </body> </html>

The Result

In the example above two paragraphs were given the class label of bright while the third paragraph was given the id of dark. Note that we attached the class name to the CSS rule by using a period as element.class, while the id is given with a pound sign as element#id. As their names suggest, we can give several elements the same class name but each id name should be unique. Also, note that we can give the same class name to different types of elements like <p> and <h1>.

Div and Span

It is often useful to group several html elements together as a single block when no larger html element naturally encloses only that group. <div> and <span> are two empty HTML elements that allow us to do this. These elements do not really have any default meaning for web browsers like, for example, the <h1> tag does. So, we can put a <div> or <span> element around other HTML elements to group them together.

These two elements are useful in the way that they give us extra control for writing CSS rules. The difference between <div> and <span> is that the former is a block displayed element while the latter is displayed as an inline element. A block display puts the element on its own horizontal line while an inline element will be displayed on the same horizontal line as other inline elements, if there is room.


<< Step 4 << >> Step 6 >>