CSS ID and Class

Whats the difference between CSS ID and Class? In principle both of them are same. But they are used for different purposes. A Class is used when our CSS Class name starts with a period (.) and when we intend to apply our CSS effects on multiple objects. In the following example we are going to use our CSS Class on different objects using Class in our html tags.

.MyText
{
 width:82px;
 height:28px;
 font-size:14px;
 font-weight:bold;
}

Now lets apply the above CSS Class .MyText on different HTML Elements. 

<p class=MyText>This is my paragraph text</p>

<h1 class=MyText>My Heading one</h1>

In the above example both paragraph and heading one will look same because same css class is being applied on them.

CSS ID 

On the other hand an ID is used when our CSS Class name starts with a hash (#) and when we intend to apply our CSS effects on only one element. Mostly when we design our web page layouts we use and ID with Div. In the example below we have defined a web page layout using ID and Div.

#wrap{ 
 margin: 0 auto; /* the auto margins (in conjunction with a width) center the page */
}

#wrap #header{
 background:#FFFFFF url(images/header_bg.jpg) repeat-x;
 height:178px;
}

#wrap #footer{
 background:#FFFFFF url(images/footer_bg.jpg) repeat-x;
 height:180px;
}

#wrap #main{
 height:400px; 
}

In the above example #wrap #header means that header is a child of wrap class. In the same way footer and main are also child of wrap class.

Now lets have a look at how we can apply these different CSS Classes wrap, header, footer, main on our HTML page using ID inside Div Tag.

<div id="wrap">

<div id="header"></div>
<div id="main"></div>
<div id="footer"></div>

</div>