I know we can provide styling and positioning in CSS for text box, text area, buttons etc. using “Class” , “Id” etc. attributes to identifying an element.
My question is:
How do we decide when to use a particular attribute?
Is there any advantage of using one over other (class vs Id vs other)?
Why do we have multiple ways of identifying elements? Why not have one standard way to identifying such as, lets say “Id”?
Thanks in advance
You can’t use ID everywhere because only one element is allowed to have a given ID, so if you want to apply the same style to five different elements, you’d have to create five different rules, which is pointless.
It’s usually best to use a baseline definition for how you want certain element types to appear generally (links, lists, tables, etc.). Then if you have specific places where you want those elements to have different styles, apply a class to an element to identify that place (“navigation-bar”, e.g.), and use custom styles to modify the behavior of elements within that area:
Due to the way the styles “cascade”, properties set by the second rule will override the properties set by the first because the second selector is more specific.
As far as why there are multiple ways available to select an element, it’s because they’re pretty much all useful at one point or another. CSS helps reduce maintenance costs because you don’t have to repeat the same styling information in a bunch of different places. It can only do this if you can come up with a rule that makes it possible to match the elements you want in a variety of different situations.