Difference between id and class in CSS and when to use it

advertisements

This question already has an answer here:

  • div class vs id 22 answers
<style>
    #main{
        background: #000;
        border: 1px solid #AAAAAA;
        padding: 10px;
        color: #fff;
        width: 100px;
    }
</style>

<div id="main">
    Welcome
</div>

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

OR

<style>
    .main{
        background: #000;
        border: 1px solid #AAAAAA;
        padding: 10px;
        color: #fff;
        width: 100px;
    }
</style>
<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 confused while dealing with this.


For more info on this click here.

Example

<div id="header_id" class="header_class">Text</div>

#header_id {font-color:#fff}
.header_class {font-color:#000}

(Note that CSS uses the prefix # for IDs and . for Classes.)

However color was an HTML 4.01 <font> tag attribute deprecated in HTML 5. In CSS there is no "font-color", the style is color so the above should read:

Example

<div id="header_id" class="header_class">Text</div>

#header_id {color:#fff}
.header_class {color:#000}

The text would be white.