Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between classes and IDs in CSS? Explain with example of where to use [duplicate]

Tags:

html

css

Where can I use ids and classes? What is the difference between them? Is there any need that we should compulsorily use ids in our CSS?

like image 640
Rajasekar Avatar asked Aug 01 '09 01:08

Rajasekar


People also ask

What is the difference between IDs and classes in CSS?

Difference between id and class attribute: The only difference between them is that “id” is unique in a page and can only apply to at most one element, while “class” selector can apply to multiple elements.

What is the difference between id and class give examples where would you use them?

The difference between an ID and a class is that an ID is only used to identify one single element in our HTML. IDs are only used when one element on the page should have a particular style applied to it. However, a class can be used to identify more than one HTML element.

What are IDs used for in CSS?

The CSS id Selector The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.


1 Answers

IDs are meant to be unique, while classes are better for a "type" of element.

So you might have something like:

<ul id="menu">
....
</ul>

Because you will probably only have 1 main menu on your site.

For classes, however, you might have something like:

<span class='author'>Paolo Bergantino</span>

Or perhaps to style the div that contains an answer on this site:

<div class='answer'>....</div>

Because there will be multiple of these per page, they are a class of elements. Think of an ID as the social security number of an element. Whenever an element is important enough and is unique, you give it an ID. This also helps with dynamic websites as selecting elements by ID is by far the fastest way, and if you have multiple elements with the same ID (thus violating this practice) Javascript won't work as intended.

like image 108
Paolo Bergantino Avatar answered Sep 23 '22 01:09

Paolo Bergantino