在过去,我总是使用下划线来定义HTML中的类和id属性。在过去的几年里,我把破折号换成了破折号,主要是为了让自己与社区的趋势保持一致,不一定是因为这对我来说有意义。
我一直认为破折号有更多的缺点,我没有看到好处:
代码完成和编辑
大多数编辑器将破折号作为单词分隔符,因此我无法通过tab键找到我想要的符号。假设这个类是“featured-product”,我必须自动完成“featured”,输入一个连字符,并完成“product”。
带有下划线的“featured_product”被视为一个单词,因此它可以在一个步骤中填充。
这同样适用于在文档中导航。按单词跳转或双击类名会被连字符打断。
(更一般地,我认为类和id是标记,所以对我来说,标记应该如此容易地在连字符上拆分是没有意义的。)
算术运算符的模糊性
使用破折号破坏了JavaScript中对表单元素的对象属性访问。这只适用于下划线:
form.first_name.value='Stormageddon';
(不可否认,我自己没有这样访问表单元素,但当决定将破折号和下划线作为通用规则时,考虑到有人可能会这样做。)
像Sass这样的语言(特别是在Compass框架中)已经将破折号作为标准,甚至对于变量名也是如此。他们一开始也使用下划线。事实是,这种不同的解析方式让我感到奇怪:
$list-item-10
$list-item - 10
跨语言变量命名不一致
以前,我经常在PHP、ruby、HTML/CSS和JavaScript中为变量写下划线。这很方便,也很一致,但为了“适应”,我现在使用:
HTML/CSS中的破折号
JavaScript中的camelCase
在PHP和ruby中的underscore_case
这并没有给我带来太大的困扰,但我想知道为什么它们变得如此不一致,似乎是故意的。至少下划线可以保持一致性:
var featured_product = $('#featured_product'); // instead of
var featuredProduct = $('#featured-product');
这些差异导致我们不得不不必要地翻译字符串,同时还可能出现错误。
所以我问:为什么社区几乎都选择破折号,还有什么比下划线更重要的原因吗?
在这开始的时候,有一个相关的问题,但我的观点是,这不是(或不应该)只是一个品味的问题。我很想知道为什么我们都选择了这个惯例如果这真的只是一个品味问题的话。
也许HTML/CSS社区使用破折号而不是下划线的一个关键原因是由于规范和浏览器实现的历史缺陷。
来自2001年3月发布的Mozilla文档@ https://developer.mozilla.org/en-US/docs/Underscores_in_class_and_ID_Names
The CSS1 specification, published in its final form in 1996, did not
allow for the use of underscores in class and ID names unless they
were "escaped." An escaped underscore would look something like this:
p.urgent\_note {color: maroon;}
This was not well supported by browsers at the time, however, and the
practice has never caught on. CSS2, published in 1998, also forbade
the use of underscores in class and ID names. However, errata to the
specification published in early 2001 made underscores legal for the
first time. This unfortunately complicated an already complex
landscape.
我通常喜欢下划线,但反斜杠只会让它变得丑陋得无法想象,更不用说当时的稀缺支持了。我可以理解为什么开发者像躲避瘟疫一样躲避它。当然,我们现在不需要反斜杠,但是破折号的礼节已经牢固地建立起来了。
也许HTML/CSS社区使用破折号而不是下划线的一个关键原因是由于规范和浏览器实现的历史缺陷。
来自2001年3月发布的Mozilla文档@ https://developer.mozilla.org/en-US/docs/Underscores_in_class_and_ID_Names
The CSS1 specification, published in its final form in 1996, did not
allow for the use of underscores in class and ID names unless they
were "escaped." An escaped underscore would look something like this:
p.urgent\_note {color: maroon;}
This was not well supported by browsers at the time, however, and the
practice has never caught on. CSS2, published in 1998, also forbade
the use of underscores in class and ID names. However, errata to the
specification published in early 2001 made underscores legal for the
first time. This unfortunately complicated an already complex
landscape.
我通常喜欢下划线,但反斜杠只会让它变得丑陋得无法想象,更不用说当时的稀缺支持了。我可以理解为什么开发者像躲避瘟疫一样躲避它。当然,我们现在不需要反斜杠,但是破折号的礼节已经牢固地建立起来了。