简体   繁体   English

“不要在选择器 (CSS) 中使用 ID” 那么,用什么来代替 ID?

[英]“Don't use IDs in selectors (CSS)” then, what to use instead of IDs?

One of CSS lint rules is: "It's better to not use IDs in selectors". CSS lint 规则之一是:“最好不要在选择器中使用 ID”。 So, what should we use instead of IDs to point to a unique element?那么,我们应该使用什么来代替 ID 来指向一个唯一元素? For example, say I have dozens of elements that have a class named my-class , and I want only one of them to have a special CSS property.例如,假设我有几十个元素有一个名为my-class ,我只希望其中一个具有特殊的 CSS 属性。 What can I do?我能做什么?

CSS-lint should be 'fixed' or rather updated to modern standard because its based on more than 10 year old code base where support for IE6 and IE7 where still preferable. CSS-lint 应该“修复”或者更新为现代标准,因为它基于超过 10 年的旧代码库,其中对 IE6 和 IE7 的支持仍然更可取。

Nowadays everyone should know ID's are the fastest css selectors followed by Classes, Dom tags, adjacent siblings etc. And that CSS reads from right to left.现在每个人都应该知道 ID 是最快的 css 选择器,其次是类、Dom 标签、相邻的兄弟等。而且 CSS 从右到左读取。 So the shortest selector is the fastest.所以最短的选择器是最快的。 Since #ID is the fastest selector and #ID (should be) unique its ridicule to not use the #id as selector in CSS.由于#ID 是最快的选择器,而#ID(应该)是独一无二的,它嘲笑在 CSS 中不使用 #id 作为选择器。

give them another class for example:给他们另一堂课,例如:

<div class="myClass special"></div>

.myClass.special{
  color: red;
}

You could add an additional class to the element and specify it in your css instead of ids.您可以向元素添加一个额外的类,并在您的 css 中指定它而不是 ids。 ID selectors have a higher specificity than attribute selectors but using ids in css isn't recommended and can't be reused. ID 选择器比属性选择器具有更高的特异性,但不推荐在 css 中使用 id 并且不能重复使用。 CSS classes can do everything IDs can. CSS 类可以做 ID 可以做的一切。

One of CSS lint rules is: "It's better to do not use IDs in selectors". CSS皮棉规则之一是:“最好不要在选择器中使用ID”。 So, what should we use instead of IDs to point at a unique element?那么,我们应该使用什么代替ID来指向唯一元素? For example, I have hundreds of elements which have a class named "myClass", and I want one of them to have a special CSS property separately.例如,我有成百上千个具有名为“ myClass”的类的元素,并且我希望其中一个具有单独的特殊CSS属性。 What can I do?我能做些什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM