This question already has an answer here:
<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.
id selector can be used to more elements. here is the example:
css:
html:
I tested on internet explorer (ver. 11.0) and Chrome (ver.47.0). it works on both of them.
The "unique" only means one element can not have more than one id attributes like class selector. Neither
nor
As pretty much everyone else has said use ID for one-off elements and class for multiple use elements.
Here is a quick, over simplified example, take HTML and HEAD tags as read
Also, as mentioned in other answers ID are well exposed to javascript, classes less so. However modern javascript frameworks like jQuery leverage class for javascript too
IDs must be unique--you can't have more than one element with the same ID in an html document. Classes can be used for multiple elements. In this case, you would want to use an ID for "main" because it's (presumably) unique--it's the "main" div that serves as a container for your other content and there will only be one.
If you have a bunch of menu buttons or some other element for which you want the styling repeated, you would assign them all to the same class and then style that class.