Let’s consider these 2 ways of writing the same code:
Method 1
<div id="header">
<div id="user">
<a id="userName">Username</a>
<a id="userImage">Userimage</a>
</div>
</div>
Method 2
<div id="header">
<div class="user">
<a class="name">Username</a>
<a class="image">Userimage</a>
</div>
</div>
CSS of Method 1
#userName { color: white; }
#userImage { height: 50px; width: 50px; }
CSS of Method 2
#header div.user a.name { color: white; }
#header div.user a.image { height: 50px; width: 50px; }
It seems to me that Method 2 is cleaner, since you will never end up with IDs like userImageInnerBox. Now technically speaking which is the best method and why?
The golden rules goes as this: use
idfor chrome elements, useclassfor content elements. So method 2 is the better.You can read this article on css-discuss for inspiration: http://css-discuss.incutio.com/wiki/Classes_Vs_Ids
There is nothing that stops you from using
idattributes on unique content elements, and in some cases it can be a nice way to speed up javascript DOM traversals. For styling purposes, however, it is considered by many as bad practice.The main points to consider are these:
Whenever I use
idattributes on non-chrome elements it is purely for fast javascript access, and never for styling.