ID and Classes in CSS

This article explains the basic meaning and the need of ID and Classes in CSS(Cascading style sheet).  We use CSS mainly to decorate presentation side of any web page on the web.  Many fellow developers also had some discussion over Table layouts and CSS layouts before above concept.  Most of them feel that table layout is good than CSS layout, in which developer can easily structure whole web page according to their requirement.  But by the time many professional developers/designers knows the benefits of web standards and understand the need of CSS based layouts.

Note: Table based layout mostly used in database driven applications where developer need to select, update, delete and insert data into the database.

With the evolution of HTML 5 many developers have started adopting CSS based layouts with the concept of ID and Classes in their applications.

Sample Example:

<ul id=”boo”>
<li><a href = “/samplepage1″>Services</a></li>
<li><a href = “/samplepage1″>about us</a></li>
<li><a href = “/samplepage1″>feedback</a></li>
<li><a href = “/samplepage1″>privacy</a></li>
</ul>

ID:  I would like to explain this concept with above mentioned program.  An ID is used to identify a specific element, such as the site navigation and must be unique to that page.  ID are useful for identifying persistent structural elements such as the main navigation or content areas.

Classes:  As a single ID name can only be applied to one element on a page, while on the other side classes can be applied to any number of elements on a page.  This makes classes very powerful than ID.  Classes are useful for identifying types of content or similar items.

For Example:

/* CSS style */

<style>

/* '.' sign is for Classes */ 

.lg  {   height:200px;
width: 100px;
float:left;    }

/* '#' sign is for ID */

#lg  {   height:200px;
width: 100px;
float:left;    }

</style>

Rather than giving each element a separate ID, we can give one class to different – different element.

<!– using CSS styles in similar items –>

1)  <a href=”#” class = “lg” >About us </a>

2)   <p class = “lg” >services </p>

3)   <strong class = “lg” >Contact us </strong>

Novice developers/designers must need to pay attention while writing Class and ID names because the names are case-sensitive.  And the browsers assumes “.lg” and “.LG” are two different words.  To avoid such mistakes developer/designer need to be consistent and simple with naming conventions.

Note: Always remember general rule while designing web page with CSS that classes should be applied to conceptually similar items that could appear in multiple places on the same page, whereas ID should be applied to unique elements.

Uploaded by: Author