[关闭]
@a06062125 2016-06-04T17:06:20.000000Z 字数 1485 阅读 347

IDs | MaintainableCSS - an approach to writing modular, scalable and maintainable CSS | By Adam Silver

zcfy maintainablecss


IDs

ID

Summary: Don’t use IDs as hooks for styling.

概要: 禁止使用 ID 作为样式的钩子。

Why shouldn’t we use IDs for CSS?

为什么不该在 CSS 样式表中使用 ID 选择器

Because of specificity issues.

唯一性问题

IDs overpower class names by orders of magnitude. For this reason you can’t override an ID selector’s style with a class name selector easily.

IDs overpower class names
ID 选择器的优先级远远大于类名选择器。因此,想要用类名选择器覆盖 ID 选择器的样式是件很难的事。

This becomes a problem when you need a way to provide additional meaning to the HTML, such as state, something we discuss in a chapter of its own.

当我们需要给HTML赋予诸如状态(关于状态有独立章节深入讨论)等等的附加含义时, 会变得比较麻烦。

  1. #someModule {
  2. color: red;
  3. }
  4. .someModule-override {
  5. color: blue;
  6. }

If you apply the ID and the class name to the element, the colour will always be red.

如果有一个元素的 id 值为someModule , 同时它的 class 值为someModule-override 的类, 它的文本总会是红色。

  1. .someModule {
  2. color: red;
  3. }
  4. .someModule-override {
  5. color: blue;
  6. }

Now the colour will be blue as intended.
现在颜色就会如预期一样变成蓝色了。

But, sometimes an ID is required?

但是, 有时ID是必须的?

Sometimes using IDs is necessary. For example a form control is linked to a label by ID. And internal anchors are often bound using IDs too. Both of these improve the User Experience. Use as appropriate for additional behaviour, not for styling.

有时必须用到 ID。 比如,表单控件通过 ID 关联到某个 label 。 内部的锚点也通过 id 进行绑定。 它们都起到了提升用户体验的作用。这些情况下 , ID 适当地提升附加行为, 而不是作为添加样式之用。

Final thoughts on IDs

关于 ID 最后的思考

Avoid IDs as hooks for styling but if you need them for other things use them. As and when you do use IDs, stick to the naming conventions you would use for classes as explained in other chapters.

避免使用 ID 作为样式的钩子, 但是要实现其它需求时那就用吧。使用 ID 时, 坚持命名规范,就像给类命名时一样。 详细说明请见其它章节。
在此输入正文

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注