問題描述
讓我們考慮這兩種編寫相同代碼的方式:
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.
這篇關于哪種方法更好?CSS類或ID?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!