哪种方法更好? CSS类或ID的? [英] Which method is better? CSS classes or ID's?
问题描述
让我们考虑这两种编写相同代码的方法:
Let's consider these 2 ways of writing the same code:
方法1
<div id="header">
<div id="user">
<a id="userName">Username</a>
<a id="userImage">Userimage</a>
</div>
</div>
方法2
<div id="header">
<div class="user">
<a class="name">Username</a>
<a class="image">Userimage</a>
</div>
</div>
方法1的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是更干净,因为你永远不会结束, code> userImageInnerBox 。现在从技术上讲这是最好的方法,为什么?
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?
推荐答案
黄金规则如下:use id
,对于内容元素使用 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.
这篇关于哪种方法更好? CSS类或ID的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!