CSS类命名约定

bob*_*obo 65 css naming-conventions

在网页上,有两个控件块(主要和次要),大多数人会使用哪些类名?

选择1:

<div class="primary controls">
 <button type="button">Create</button>
</div>

<div class="secondary controls">
 <button type="button">Edit</button>
 <button type="button">Remove</button>
</div>
Run Code Online (Sandbox Code Playgroud)

选择2:

<div class="primary-controls controls">
 <button type="button">Create</button>
</div>

<div class="secondary-controls controls">
 <button type="button">Edit</button>
 <button type="button">Remove</button>
</div>
Run Code Online (Sandbox Code Playgroud)

Iva*_*nov 81

直接问题的答案是正确的在这之下,由柯特.

如果您对CSS类命名约定感兴趣,我建议考虑一个名为BEM(Block,Element,Modifier)的非常有用的约定.

UPDATE

请在这里阅读更多相关信息 - http://getbem.com/naming/ - 这是一个较新的版本,使得以下答案过时.


主要原则:

  • 页面由独立块构成.Block是一个HTML元素,类名称具有"b-"前缀,例如"b-page"或"b-login-block"或"b-controls".

  • 所有CSS选择器都基于块.不应该有任何不以"b-"开头的选择器.

好:

.b-controls .super-control { ... }
Run Code Online (Sandbox Code Playgroud)

坏:

.super-control { ... }
Run Code Online (Sandbox Code Playgroud)
  • 如果你需要另一个块(在另一个页面上),这个块类似于你已经拥有的块,你应该为你的块添加一个修饰符而不是创建一个新的块.


例:

<div class="b-controls">
    <div class="super-control"></div>
    <div class="really-awesome-control"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

带修饰符:

<div class="b-controls mega"> <!-- this is the modifier -->
    <div class="super-control"></div>
    <div class="really-awesome-control"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

然后你可以在CSS中指定任何修改:

.b-controls { font: 14px Tahoma; }
.b-controls .super-control { width: 100px; }

/* Modified block */
.b-controls.mega { font: 20px Supermegafont; }
.b-controls.mega .super-control { width: 300px; }
Run Code Online (Sandbox Code Playgroud)

如果您有任何问题,我很乐意与您讨论.我已经使用BEM两年了,我声称这是我见过的最好的会议.

  • @ClaudioLudovicoPanetta 在这个特定的约定中,建议您不要对 css 样式使用 id。使用它们没有优点,但有很大的缺点。 (2认同)
  • @ClaudioLudovicoPanetta 的缺点是 id 应该是唯一的,并且没有特别的理由说明样式应该是唯一的。 (2认同)

Cur*_*urt 24

我会选择:

<div class="controls primary">
 <button type="button">Create</button>
</div>

<div class="controls secondary">
 <button type="button">Edit</button>
 <button type="button">Remove</button>
</div>
Run Code Online (Sandbox Code Playgroud)

只要您的CSS结构正确,primary并且secondary不应与应用程序上的任何其他内容发生冲突:

.controls.primary {}
Run Code Online (Sandbox Code Playgroud)

请注意,我还controls提前primary/ secondary在代码中,因为这是您的主要类.

我认为下面的第一组比第二组更具可读性:

.controls.primary {}
.controls.secondary {}


.primary.controls {}
.secondary.controls {}
Run Code Online (Sandbox Code Playgroud)