What is the difference between id and class in CSS, and when should I use them?

J.K.A. picture J.K.A. · Oct 15, 2012 · Viewed 436.9k times · Source
#main {
    background: #000;
    border: 1px solid #AAAAAA;
    padding: 10px;
    color: #fff;
    width: 100px;
}
<div id="main">
    Welcome
</div>

Here I gave an id to the div element and it's applying the relevant CSS for it.

OR

.main {
    background: #000;
    border: 1px solid #AAAAAA;
    padding: 10px;
    color: #fff;
    width: 100px;
}
<div class="main">
    Welcome
</div>

Now here I gave a class to the div and it's also doing the same job for me.

Then what is the exact difference between Id and class and when should I use id and when should I use class.? I am a newbie in CSS and Web-design and a little bit confused while dealing with this.

Answer

lc. picture lc. · Oct 15, 2012
  • Use a class when you want to consistently style multiple elements throughout the page/site. Classes are useful when you have, or possibly will have in the future, more than one element that shares the same style. An example may be a div of "comments" or a certain list style to use for related links.

    Additionally, a given element can have more than one class associated with it, while an element can only have one id. For example, you can give a div two classes whose styles will both take effect.

    Furthermore, note that classes are often used to define behavioral styles in addition to visual ones. For example, the jQuery form validator plugin heavily uses classes to define the validation behavior of elements (e.g. required or not, or defining the type of input format)

    Examples of class names are: tag, comment, toolbar-button, warning-message, or email.

  • Use the ID when you have a single element on the page that will take the style. Remember that IDs must be unique. In your case this may be the correct option, as there presumably will only be one "main" div on the page.

    Examples of ids are: main-content, header, footer, or left-sidebar.

A good way to remember this is a class is a type of item and the id is the unique name of an item on the page.