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

2020-02-05 03:33发布

问题:


Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 6 months ago.

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?

回答1:

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.



回答2:

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.



回答3:

Personally I find best method is second, that is the classes was created.



回答4:

I prefer a mix of both, the names of method 1, with class rather than ID.

Method two by itself is alright but I think it could lead to css bloat later down the road, especially if you intend to continue using generic classes like name and image for other elements.



回答5:

You should use ID's for unique elements and classes for elements you use more times. That is what you need, classes.



回答6:

If there will only ever be one element user or userName then ID is better. The CSS selector for it will be more efficient. This will also be true if you need to select it for use in JavaScript.

Class should be used when there might be more than one element that should be styled the same way.