What is the difference between class and id selector in CSS?

Dung Do Tien May 28 2020 528

I have some HTML code as below:

<h1 id="title"> This is a heading page </h1>
<h2 class="title"> This is a sub heading page </h1>

And I want to set text color of them to red color:

#title{
  color: red;
}
.title {
  color: red;
}

Both #title and .title also for the same result. So can you explain to me

1. What is the difference between class in id selector in CSS?

2. When we should use class/id?

3. What are the pros and cons of them?

Have 1 answer(s) found.
  • M

    Manish Kumar May 29 2020

    A great question!!

    1. What is the difference between class in id selector in CSS?

    - The id stands for identity, in a HTML page you can not have more than one HTML tag with the same id. So id is unique.

    - The class is not unique so many tags can have the same class value.

     

    2. What are the pros and cons of them?

    - The class can reusable for many tags, it helps reduce code style and sometimes easily maintain to change the style for many tags with the same style.

    - Id always has a priority higher than class.

    - The id can not reusable because it is unique.

    - If you have a big website with thousands of line codes and if you can not be controlled class, it very easy to make some degrade style to another tag.

     

    3. When we should use class/id?

    Base on the pros and cons of them, you need to be defined what is unique and what is need reusable. From there you will know when to use the id and the class.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close