哪种方法更好?CSS类或ID?
让我们考虑这两种编写相同代码的方式:
Let's consider these 2 ways of writing the same code:
方法一
<div id="header">
<div id="user">
<a id="userName">Username</a>
<a id="userImage">Userimage</a>
</div>
</div>
方法二
<div id="header">
<div class="user">
<a class="name">Username</a>
<a class="image">Userimage</a>
</div>
</div>
方法一的CSS
#userName { color: white; }
#userImage { height: 50px; width: 50px; }
方法2的CSS
#header div.user a.name { color: white; }
#header div.user a.image { height: 50px; width: 50px; }
在我看来,方法 2 更简洁,因为您永远不会得到像 userImageInnerBox
这样的 ID.现在从技术上讲,哪种方法最好,为什么?
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?
推荐答案
黄金法则是这样的:chrome 元素使用 id
,content 元素使用 class
.所以方法2更好.
The golden rules goes as this: use id
for chrome elements, use class
for content elements. So method 2 is the better.
您可以在 css-discuss 上阅读这篇文章以获得灵感:http://css-discuss.incutio.com/wiki/Classes_Vs_Ids
You can read this article on css-discuss for inspiration: http://css-discuss.incutio.com/wiki/Classes_Vs_Ids
没有什么可以阻止您在独特的内容元素上使用 id
属性,并且在某些情况下,它可能是加速 javascript DOM 遍历的好方法.然而,出于造型目的,它被许多人认为是不好的做法.
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.
要考虑的要点是:
- 类可以用于多重继承,id必须是唯一的
- 如果您需要将继承与 id 样式配对使用,选择器的特殊性可能会成为一场噩梦
每当我在非 Chrome 元素上使用 id
属性时,它纯粹是为了快速访问 javascript,而不是为了样式.
Whenever I use id
attributes on non-chrome elements it is purely for fast javascript access, and never for styling.
相关文章