0
ID vs CLASS in CSS
Someone please help me understand: What exactly is the point of using an ID with your selector in css instead of just using classes for everything? Is it necessary to have ID’s? What purpose do they serve?
4 Respostas
+ 6
Maybe this analogy will help:
Why does your postman require your house to have a unique address? Why does he not call every house ".house"?
Sometimes you need to target a specific thing, in javascript you do it a lot as others have said. Sure, you could use a class instead of an ID and say to yourself "let's use it only once", but you will still never have the uniqueness guarantee that an ID gives you, and it's bad practice to use classes that way. Classes are for many things, ID's for one.
+ 3
It will come in handy, when you'll use JavaScript & JQuery. It will help you to manupulate them by using ID (and class also). ^_^
+ 2
You can give as many Classes you want with the same name.
But the ID of an element will be unique.
+ 1
Each element can have any number of classes, and they will all effect it, though some will override the effects of others based on the specificity of the CSS selector used to apply style. e.g. whether they're inline (style="attribute: value") or part of a stylesheet. Pretty sure there's more to this too, but I can't 100% remember.
The ID of each element is supposed to be unique, but if there are multiple elements with the same ID the first one takes precedence and the others will be ignored unless you handle them specially. e.g. loop through the elements and check for id="wantedID" rather than using document.getElementById or $( "#jQueryIDSelector" ).
Edit: typo correction.