The ID Attribute

The ID attribute is used to define a unique style or section of a page. Each id attribute must have a unique name and can only be used once per page.

Id attribute for page structure

The id attribute is commonly used on the div's used for the page structure. By using them this way helps to keep your page properly structured. With Valid Web Designs the main style sheet has a an id of wrapper.


#wrapper{
width:995px;
margin:0 auto;
text-align:left;
overflow:hidden;
border-left:1px solid #580000;
border-right:1px solid #580000;
background:#fdfaf1 url(../assets/wrapper.jpg) repeat-y;
}

This sets the main containing div for the entire page structure. If it were to be inadvertently placed in the HTML a second time it could affect the way the page displays.

Following this the other sections of the page structure that are to be used only once have an id attribute.

Id attribute as a link identifier

The id attribute can also be used as link/content identifiers. Example for this would be allowing a visitor to click on a link, this link would take them to a particular section of the existing page or of another page.

To use the ID attribute for this purpose it is not required to be in the CSS Style sheet since it doesn't have any styling attributed to it.

Let's view this in action

The h1 element at the top of this page has an id of h1
<h1 id="h1">The ID Attribute</h1>

The html for the link that will take us to this section.
<p><a href="#h1">Take me to the first section of this page</a></p>

Now click - Take me to the first section of this page

Sweet, now let's view a link that will take us to the second section of the class attribute page.

<p><a href="class-attribute.php#classes">Take me to the second section of the class attributes page</a></p>

Take me to the second section of the class attributes page

Just hit your browser back button to return here.

Id attribute for styling

Styling can be applied to HTML elements through the id attribute. Just set it up like you would with the class attribute. Remember that an id can only be used once per page.

<h1 id="welcome">Welcome to the Valid Web Designs CSS tutorial.</h1>