CSS tags – id vs. class

The `tags war`

To class or not to class? This is the question … for this blog entry. Let’s try and find the answer with the help of an analogy to OOP.

CSS and OOP?

I reckon most of you already know what OOP stands for but for those who don’t, OOP stands for Object Oriented Programming – the classes-objects-inheritance concepts used in code writing and code design with the ultimate goal of maximizing code reuse. So, what do CSS tags and Object Oriented Programming have in common? And most important, how can OOP concepts help us decide which tag is better suited for the job. At a first glance, class is a reserved word in both languages, so maybe we can start from there. :)

So, class is class?

Coincidence or not, the CSS class has similar behaviour with the classes from OO programming languages. Let’s say you want all the h3 tagged text on the page to be underlined. You could write a CSS class for h3 and specify “text-decoration: underline;”. Each time you will use the h3 tag the text formatting will include an underline. So basically you are using the CSS class “template” to create multiple instances of h3 text and that is exactly what OOP classes are (among other things): templates for objects.

Then id is an object?

The CSS id tag is still used as a class in order to define the “shape” of the element that will have the id assigned. However, the id tag is usually used to pinpoint an unique object on the web page. Tracking elements by unique ids is a useful technique (i.e. when using Javascript methods to update or modify elements, when parsing POST form variables in PHP, etc.). Think of the id tag as a class with a single object or the class/object concept merged. It’s like that philosophical question: what is the shape of a chair? When you think of a chair you think about the shape or the object itself?

Conclusions

The answer to our initial question is now simple: use the CSS class tag when you need to tag or modify the format of more than 1 element in the web page and use the CSS id tag when you need to pinpoint to a specific element in the web page (something like the “You are here!” signs in the shopping malls).

Post a Comment

Your email is never published nor shared. Required fields are marked *

CAPTCHA image