CSS类命名约定 [英] CSS class naming convention
问题描述
在网页上,有两个控制块(主要和次要),大多数人使用什么类名?
On a web page, there are two blocks of controls (primary and secondary), what class names would most people use?
选择1: / strong>
Choice 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>
选择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>
推荐答案
问题的直接回答是正下方这个,由Curt。
The direct answer to the question is right below this one, by Curt.
如果你对css感兴趣类命名约定我建议考虑一个非常有用的约定BEM(Block,Element,Modifier)。
If you're interested in css class naming conventions I suggest to consider one very useful convention named BEM (Block, Element, Modifier).
UPD。请在这里阅读更多 - http://getbem.com/naming/ - 这是一个更新的版本,使以下答案过时。
UPD. Please read more about it here - http://getbem.com/naming/ - that's a newer version that renders the following answer obsolete.
主要原则:
-
。 Block是一个类名为b-前缀的html元素,例如b-page或b-login-block或b-controls。
A page is constructed from independent Blocks. Block is an html element which class name has a "b-" prefix, such as "b-page" or "b-login-block" or "b-controls".
所有css选择器都基于块。不应该有任何不以b-开头的选择器。
All css selectors are based on blocks. There shouldn't be any selectors that aren't started with "b-".
好:
.b-controls .super-control { ... }
错误:
.super-control { ... }
- 如果你需要另一个块(在另一个页面上),类似于你已经拥有的块,你应该在你的块中添加一个修饰符,而不是创建一个新的一个。
示例:
<div class="b-controls">
<div class="super-control"></div>
<div class="really-awesome-control"></div>
</div>
使用修饰符:
<div class="b-controls mega"> <!-- this is the modifier -->
<div class="super-control"></div>
<div class="really-awesome-control"></div>
</div>
然后您可以在css中指定任何修改:
Then you can specify any modifications in 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; }
如果您有任何问题,我很乐意与您讨论。我一直在使用BEM两年,我声称这是我见过的最好的约会。
If you have any questions I'd be pleased to discuss it with you. I've been using BEM for two years and I claim that this is the best convention I've ever met.
这篇关于CSS类命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!