ID vs. Class in CSS

ID vs. Class in CSS
0

#1

What are the key differences between IDs and classes in CSS? Is there a fundamental reason why you should use one over the other in certain situations? And what kind of situation would dictate the use of one in place of another.

Happy coding. :slight_smile:


#2

I believe this was covered in the FCC curriculum somewhere under the CSS section. Basically ‘id’ is a more specific/targeted form of tag identification with the css file. Class (as the name suggests) is more general and groups tags together (who share similar characteristics for eg.).

I may want to ‘id’ (identify) a specific tag for its unique behaviour and looks.
I may want to ‘class’ (group) a set of tags for their common behaviour and looks.


#3

class is reusable whereas ids is only used only once.

for example suppose u have 2h2 tags.

h2 class=“something”> something</h2
h2 class=“something”>something</h2

by using .something{

}//you target both h2.

whereas Ids is something u only target only once , for example an

input type=
“button” id=“button-target”> </input
// since its only once you can only use the id once.

in terms of specificity Id has higher specificity than classes.

so using another example

#something{
color:red
}

and u use .something{
color:blue
{ // the id will win even though .something class came later. Because the element will be red in color.

in general use classes in css, i have never use ids for css and only use ids , for links for redirection of page to a part of your page , or use it for DOM in javascript

note i intentionally leave out the < in my examples since the post will censor the code


#4

Thank you kindly for your reply. I may have breezed through the tutorials a little too quickly. Review is so crucial, no?


#5

Yes, whenever I have a question about something new, I always try to find it in the FCC curriculum first then if that’s not enough, I google, and if that’s not enough, I simply ask.


#6

That’s an excellent approach. I’ll have to try that from now on. :slight_smile:


#7

sounds good. Note this piece of documentation about this method:


#8

Good advice.

After following the “read” part of the suggestion, I found this article. Hopefully, someone will come across this article and make use of it. :slight_smile: