Difference Between Id And Class In Css

Difference Between Id And Class In Css

Hello....I published the following code for sharing knowledge about the differences between ID and class in CSS(Cascading Stylesheet).

In CSS, class and ID selectors are used to identify various HTML elements. The main benefit of setting class or ID is that you can present the same HTML element differently, depending on its class or ID.

Class selector: The class selector selects elements with a specific class attribute. It matches all the HTML elements based on the contents of their class attribute. The (.) symbol, along with the class name, is used to select the desired class.

Syntax Screenshot (5).png

ID selector: The ID selector matches an element based on the value of its id attribute. In order for the element to be selected, its ID attribute must exactly match the value given in the selector. The # symbol and the id of the HTML element name are used to select the desired element.

Syntax Screenshot (6).png

However,the two have a difference The difference between Class and ID selector The difference between an ID and a class is that an ID is only used to identify one single element in our HTML. An ID is actually used when we want one element on the page to have a specific style applied to it,while a class can be used to identify more than one HTML element.

These images below illustrates how class is been used to identify more than one HTML element,and how ID is used to style a single element in HTML....The first picture shows the code input while the second picture shows the outpu..

Screenshot (8).png

Screenshot (7).png

From these images,we can see that all the elements i.e the h3, the first paragraph and the second paragraph all have the same background color which is red,simply because they are in a div with the class main,but the first paragraph which reads "This paragraph has its own ID" has a different background color which is blue(the ID attribute was used to give this paragraph its own unique design)

So, this is actually the main difference between CSS class and ID....