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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With