Which method is better? CSS classes or ID#39;s?(哪种方法更好?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.
这篇关于哪种方法更好?CSS类或ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:哪种方法更好?CSS类或ID?
基础教程推荐
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
