Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which method is better? CSS classes or ID's? [closed]

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?

like image 637
Shoe Avatar asked Mar 02 '11 17:03

Shoe


2 Answers

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:

  1. classes can be used for multiple inheritance, id's needs to be unique
  2. selector specificity can become a nightmare if you need to use inheritance paired with id styling

Whenever I use id attributes on non-chrome elements it is purely for fast javascript access, and never for styling.

like image 164
Martin Jespersen Avatar answered Oct 21 '22 23:10

Martin Jespersen


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.

like image 2
jeroen Avatar answered Oct 21 '22 21:10

jeroen