What is the difference between id & class

I know for id we have to use ‘#’ symbol & for class ‘.’ symbol.
But i dont know what class does & id does i use both for styling css.
Can any one help me when i want to use id & when class.is there is any major difference.

There should only be 1 ID on a page. Class can be assigned to many different objects.

hth

For starters, a page can only have 1 unique ID (#) applied to 1 element. On the other hand a class can be applied to many elements.

Example when to use class:
You have a gallery made of 10 thumbnails, you can assign 1 class to all of them like so:

css
.thumbnail {width: 200px; height: 200px; float: left;}

HTML
<div class="thumbnail"></div>
<div class="thumbnail"></div>
<div class="thumbnail"></div>
.
.

As you see, we created 10 thumbails with only 1 class in CSS. If you going to use ID’s with a # then you will need 10 lines in css like so:

CSS
#thumbnail1 {width: 200px; height: 200px; float: left;}
#thumbnail2 {width: 200px; height: 200px; float: left;}
#thumbnail3 {width: 200px; height: 200px; float: left;}
.
.

HTML
<div id="thumbnail1"></div>
<div id="thumbnail2"></div>
<div id="thumbnail3"></div>
.
.

As you have guessed this is not practical at all.

Below is an example when to use ID with #:
Let say you have a button, when clicked the page scrolls to a certain element on the page, this can be achieved with a unique ID, because there is only 1 element on the page that the button will scroll to like so:

<a href="#contact-form"></a>
.
.
<div id="contact-form"></div>

NOTE: You can mix ID’s with classes in 1 element like so:

<div id="gallery" class="gallery-container"></div>

What can be applied in CSS for ID’s can be applied to classes. it makes no difference.

I guess there are more example and differences to mention, but can’t think of any right now.

There is an important difference between classes and IDs regarding their use in CSS selectors.
IDs have a far higher specificity weight than classes. For this reason it is generally considered best to avoid using IDs in CSS selectors in favour of using classes instead.
So usually when adding an attribute to an HTML elements for the purpose of CSS selection, it’s best to always use a class.
There are just a few special cases for using IDs in styling, such as using a :target pseudo class. But it’s best avoided unless you know what you are doing.

5 Likes

Thanks for the info @SamA74. What I meant by my statement is that CSS Styles can be applied/understood by both.

You could have more than a single class value

<div class="thumbnail first"></div> 
<div class="thumbnail second"></div> 
<div class="thumbnail third"></div> 

Then, instead of targeting an id, it could be like

div.thumbnail.second {

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.