IDs and Classes in CSS

The ID attribute is used to uniquely identify a particular tag (& it's contents) on a HTML page. Once a tag has an ID we can apply CSS styling specifically to that tag (& it's contents). This is useful to prevent the use of deprecated tags (<center>, <font>, <b>, <u>, <i>, <strong>, <hn>, etc). Let's take an example to demonstrate what I mean: a simple page with a heading of "Hello World!!" that we want as centred bold piece of text in large font, followed by a paragraph saying "Welcome to my first webpage." which we want right aligned. First let' show the wrong way:
 

  • <!DOCTYPE .... (we'll be using the transitional dtd)
  • <html>
  • <head>
  • <title>My Homepage</title>
  • </head>
  • <body>
  • <h1><center><b>Hello World!!</b></center></h1>
  • <p>
  • Welcome to my first webpage.
  • </p>
  • </body>
  • </html>



While this will probably display as expected on most browsers it is not standards compliant and so may present unexpected results. Instead, we should be trying to remove the style/layout from the content. So let's try this now.
 

  • <!DOCTYPE .... (we'll be using the transitional dtd)
  • <html>
  • <head>
  • <title>My Homepage</title>
  • <style>
  • body {
  • background-color: rgb(255,255,255);
  • color: #4D4D4D;
  • }
  •  
  • #header {
  • width: 100%;
  • text-align:center;
  • font-size: 3.6em;
  • font-weight: heavy;
  • }
  •  
  • #para1 {
  • width:100%;
  • text-align:right;
  • }
  • </style>
  • </head>
  • <body>
  • <div id="header">Hello World!!</div>
  • <div id="para1">Welcome to my first webpage.</div>
  • </body>
  • </html>



Notice how much neater the content is now. By removing the styling from the content (and making the content tags only be holders for the data and have no role in how the data is displayed). The id styling (in the style tag this is the styling marked with a # and the id of the tag you wish to apply it to) applies to <u>one</u> tag, the tag whose id matches to the styling. This is the reason that the id's must be unique.
That's great of course unless you need to apply the same style to multiple tags. So how do you do this? This is where classes come in and I'll be explaining how to apply class styling in the next blog entry. Check the blog listing regularly to keep up to date on our blog entries.

Regards,
James