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 id
for chrome elements, use class
for 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 id
attributes 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 id
attributes on non-chrome elements it is purely for fast javascript access, and never for styling.
If you are sure you are only going to have one element on the page, you can use method 1.
I prefer method 2 because I always end up re-using my styles and I mainly use ID's for layout elements (header, footer, etc.).
I would try to limit the selector as much as possible though, so if I can address the .name
like:
#header .name {
}
I would use that instead of your selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With