HTML Code Tutorial

ID Attribute

Though using the id attribute in the manner explained here is acceptable, the better option is using the class attribute for defining style settings.
See: 'When to Use Class' and 'IDs for Linking' below.

The ID attribute can be used with all HTML tags in HTML 5. It can be used with paragraph tags, division tags, table tags and form tags to name a few. Use it to create variations in similar code structures.

The attribute is placed in the tag as shown
<div ID="site-head">
To assign style sheet settings to the division which carries the site-head ID, you would place the following code in the style sheet.

#site-head { color :#FF0000;background-color :#FFFFFF}

Now if we had more than one division on the page only the text placed in the division site-head would be displayed in red text.

The code shown here would place a border around the left-body division.
#left-body { border: solid #000000 1px }

The id attribute is of great value when the goal is to produce HTML pages with very concise code. You could actually control the entire page diagramed below using a linked style sheet.

<div id="site-head"></div>
<div id="main-body">
<div id="left-body"></div>
<div id="right-body"></div>
<div id="footer"></div>

You could in theory redesign the entire website using only the linked style sheet.


When to Use Class

You might be tempted to over use the id attribute for naming elements on your web page.

If you are going to use the same element on the web page more than once, use class instead of the id attribute.

For example, if you name a division main, don't use the main division more than once on the same page.

If you have a particular configuration for an element that you want to use several times on the same page use class.

Suppose we wanted a section of our page to have a light yellow background color.

In the style sheet we might use:
div.yellow { background-color: #ffff00}

In the html code we would specify the division as <div class="yellow"></div>

If you wanted to have some of your paragraphs on a page displayed in bold underline, you would create a class.

Style sheet:
p.boldunderline { font-weight: 700; text-decoration: underline }

Html code:
<p class="boldunderline"></p>

Using id for an element used several times on a page, may work, but it will play havoc with your W3C validation.

Note: Never make this mistake: <h1 id="topsection" class="topsection">Section Header Text</h1>.
IDs must be unique.

See also: Class Attribute

IDs for Linking

The id attribute is best used as a locator for intradocument linking.

Here's how to use the id attribute for linking.

Click this Link

Did you try it?

Here's the code.
We place a unique id in the h1 header tag at the top of the page that looks like this:
<h1 id="topid">HTML Code Tutorial</h1>

The link that jumps to that location looks like this:
<a href="#topid">Click this Link</a>