No, I’m not going to talk about what ID and Class attributes are (I assume you already knew about these two). Instead, I’ll focus on how I use them in my web pages.
When I started with the HTML and CSS, I had a little confusion on the difference between the ID and Class attributes of an HTML element. Because, both attributes can be used in a CSS document to apply styles. i.e. consider a DIV element <div id=”my_id” class=”my_class”>; this element can be styled in two ways (off course, there are more than two ways, but we’ll focus on ID and Class alone), in a CSS file like;
#my_id{ /* CSS style definitions */ }
.my_class { /* some more CSS styles */ }
As you can see, we can either use ID and Class attribute to apply style to a HTML element. But, which one will you prefer over other and for what reason? Will you assign a ID or a Class to your HTML element? Even though there’s no standard for specifying how to use these two, here’s how I use them:
-
I use ID for giving a unique name to a HTML element, that can present only once in a HTML page. For example, a HTML page can have only one sidebar or one header. So, it’s logical to define a DIV with ID header or sidebar.
Using HTML ID attribute in web page
-
Use Class when a particular HTML element can come in multiple places in a HTML page. For example, if you are showing up a message to user, at multiple places, you can assign a class attribute and apply style accordingly.
Using HTML Class attribute in web pages
That’s the simple rule that I follow. What’s your strategy?
{ 3 comments }
That’s exactly how I use and it’s because ID in markup(or should I use DOM) is meant to be like your primary key in a database table.
I would say always use the class attribute for styling. ID should be used when you want to do some javascript DOM manipulation i.e. to uniquely identify some node in the DOM.
Thats a nice tip. I've often seen that both class and id are used in styling.
Comments on this entry are closed.