为什么 CSS 选择器/HTML 属性首选破折号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7560813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:48:07  来源:igfitidea点击:

Why are dashes preferred for CSS selectors / HTML attributes?

htmlcsscoding-stylenaming-conventions

提问by Andrew Vit

In the past I've always used underscores for defining classand idattributes in HTML. Over the last few years I changed over to dashes, mostly to align myself with the trend in the community, not necessarily because it made sense to me.

过去我一直使用下划线在 HTML 中定义classid属性。在过去的几年里,我改用破折号,主要是为了让自己与社区趋势保持一致,不一定是因为它对我有意义。

I've always thought dashes have more drawbacks, and I don't see the benefits:

我一直认为破折号有更多的缺点,我没有看到好处:

Code completion & Editing

代码完成和编辑

Most editors treat dashes as word separators, so I can't tab through to the symbol I want. Say the class is "featured-product", I have to auto-complete "featured", enter a hyphen, and complete "product".

大多数编辑器将破折号视为单词分隔符,因此我无法切换到我想要的符号。假设班级是“ featured-product”,我必须自动完成“ featured”,输入一个连字符,然后完成“ product”。

With underscores "featured_product" is treated as one word, so it can be filled in one step.

带下划线的“ featured_product”视为一个词,可以一步填写。

The same applies to navigating through the document. Jumping by words or double-clicking on class names is broken by hyphens.

这同样适用于浏览文档。按单词跳转或双击类名被连字符打破。

(More generally, I think of classes and ids as tokens, so it doesn't make sense to me that a token should be so easily splittable on hyphens.)

(更一般地说,我认为 classes 和 ids 作为tokens,所以对我来说,令牌应该如此容易地在连字符上拆分是没有意义的。)

Ambiguity with arithmetic operator

算术运算符的歧义

Using dashes breaks object-property access to form elementsin JavaScript. This is only possible with underscores:

使用破折号会破坏JavaScript 中表单元素的对象属性访问。这只能使用下划线:

form.first_name.value='Stormageddon';

(Admittedly I don't access form elements this way myself, but when deciding on dashes vs underscores as a universal rule, consider that someone might.)

(诚​​然,我自己不会以这种方式访问​​表单元素,但是在决定使用破折号还是下划线作为通用规则时,请考虑有人可能会这样做。)

Languages like Sass(especially throughout the Compassframework) have settled on dashes as a standard, even for variable names. They originally used underscores in the beginning too. The fact that this is parsed differently strikes me as odd:

Sass这样的语言(尤其是整个Compass框架)已经将破折号作为标准,即使对于变量名也是如此。他们最初也使用下划线。以不同方式解析的事实让我感到奇怪:

$list-item-10
$list-item - 10

Inconsistency with variable naming across languages

跨语言变量命名不一致

Back in the day, I used to write underscored_namesfor variables in PHP, ruby, HTML/CSS, and JavaScript. This was convenient and consistent, but again in order to "fit in" I now use:

过去,我曾经用underscored_namesPHP、ruby、HTML/CSS 和 JavaScript编写变量。这既方便又一致,但为了“适应”,我现在使用:

  • dash-casein HTML/CSS
  • camelCasein JavaScript
  • underscore_casein PHP and ruby
  • dash-case在 HTML/CSS 中
  • camelCase在 JavaScript 中
  • underscore_case在 PHP 和 ruby​​ 中

This doesn't really bother me too much, but I wonder why these became so misaligned, seemingly on purpose. At least with underscores it was possible to maintain consistency:

这并没有让我太困扰,但我想知道为什么这些看起来如此错位,似乎是故意的。至少使用下划线可以保持一致性:

var featured_product = $('#featured_product'); // instead of
var featuredProduct = $('#featured-product');

The differences create situations where we have to translate stringsunnecessarily, along with the potential for bugs.

这些差异造成了我们必须不必要地翻译字符串的情况,以及潜在的错误。

So I ask: Why did the community almost universally settle on dashes, and are there any reasons that outweigh underscores?

所以我问:为什么社区几乎普遍使用破折号,是否有任何理由超过下划线?

There is a related questionfrom back around the time this started, but I'm of the opinion that it's not (or shouldn'thave been) just a matter of taste. I'd like to understand why we all settled on this convention if it really was just a matter of taste.

在这开始的时候有一个相关的问题,但我认为这不仅仅是(或不应该)只是品味问题。如果这真的只是一个品味问题,我想了解为什么我们都选择了这个约定。

采纳答案by Asbj?rn Ulsberg

Code completion

代码补全

Whether dash is interpreted as punctuation or as an opaque identifier depends on the editor of choice, I guess. However, as a personal preference, I favor being able to tab between each word in a CSS file and would find it annoying if they were separated with underscore and there were no stops.

我猜,破折号是被解释为标点符号还是不透明标识符取决于选择的编辑器。但是,作为个人偏好,我更喜欢在 CSS 文件中的每个单词之间使用 Tab 键,如果它们用下划线分隔并且没有停顿,我会觉得很烦人。

Also, using hyphens allows you to take advantage of the |= attribute selector, which selects any element containing the text, optionally followed by a dash:

此外,使用连字符允许您利用|= 属性选择器,它选择包含文本的任何元素,可选地后跟一个破折号:

span[class|="em"] { font-style: italic; }

This would make the following HTML elements have italic font-style:

这将使以下 HTML 元素具有斜体字体样式:

<span class="em">I'm italic</span>
<span class="em-strong">I'm italic too</span>

Ambiguity with arithmetic operator

算术运算符的歧义

I'd say that access to HTML elements via dot notation in JavaScript is a bug rather than a feature. It's a terrible construct from the early days of terrible JavaScript implementations and isn't really a great practice. For most of the stuff you do with JavaScript these days, you'd want to use CSS Selectorsfor fetching elements from the DOM anyway, which makes the whole dot notation rather useless. Which one would you prefer?

我会说通过 JavaScript 中的点表示法访问 HTML 元素是一个错误而不是一个功能。在糟糕的 JavaScript 实现的早期,这是一个糟糕的构造,并不是一个很好的实践。对于现在使用 JavaScript 所做的大多数事情,无论如何您都希望使用CSS 选择器从 DOM 中获取元素,这使得整个点表示法变得毫无用处。你更喜欢哪一个?

var firstName = $('#first-name');
var firstName = document.querySelector('#first-name');
var firstName = document.forms[0].first_name;

I find the two first options much more preferable, especially since '#first-name'can be replaced with a JavaScript variable and built dynamically. I also find them more pleasant on the eyes.

我发现前两个选项更可取,特别是因为'#first-name'可以用 JavaScript 变量替换并动态构建。我也发现它们在眼睛上更令人愉悦。

The fact that Sass enables arithmetic in its extensions to CSS doesn't really apply to CSS itself, but I do understand (and embrace) the fact that Sass follows the language style of CSS (except for the $prefix of variables, which of course should have been @). If Sass documents are to look and feel like CSS documents, they need to follow the same style as CSS, which uses dash as a delimiter. In CSS3, arithmetic is limited to the calcfunction, which goes to show that in CSS itself, this isn't an issue.

Sass 在其对 CSS 的扩展中启用算术这一事实并不真正适用于 CSS 本身,但我确实理解(并接受)Sass 遵循 CSS 的语言风格这一事实($变量的前缀除外,这当然应该已经@)。如果 Sass 文档要看起来和感觉像 CSS 文档,它们需要遵循与 CSS 相同的样式,使用破折号作为分隔符。在 CSS3 中,算术仅限于calc函数,这表明在 CSS 本身中,这不是问题。

Inconsistency with variable naming across languages

跨语言变量命名不一致

All languages, being markup languages, programming languages, styling languages or scripting languages, have their own style. You will find this within sub-languages of language groups like XML, where e.g. XSLTuses lower-case with hyphen delimiters and XML Schemauses camel-casing.

所有语言,包括标记语言、编程语言、样式语言或脚本语言,都有自己的风格。您会在 XML 等语言组的子语言中找到这一点,例如XSLT使用带连字符分隔符的小写字母,而XML Schema使用驼峰式大小写。

In general, you will find that adopting the style that feels and looks most "native" to the language you're writing in is better than trying to shoe-horn your own style into every different language. Since you can't avoid having to use native libraries and language constructs, your style will be "polluted" by the native style whether you like it or not, so it's pretty much futile to even try.

一般来说,您会发现采用感觉和看起来最适合您所用语言的风格比试图将自己的风格硬塞到每种不同的语言中要好。由于您不可避免地必须使用原生库和语言结构,无论您喜欢与否,您的风格都会被原生风格“污染”,因此即使尝试也是徒劳的。

My advice is to not find a favorite style across languages, but instead make yourself at home within each language and learn to love all of its quirks. One of CSS' quirks is that keywords and identifiers are written in lowercase and separated by hyphens. Personally, I find this very visually appealing and think it fits in with the all-lowercase (although no-hyphen) HTML.

我的建议是不要跨语言找到最喜欢的风格,而是让自己熟悉每种语言并学会喜欢它的所有怪癖。CSS 的一个怪癖是关键字和标识符以小写形式编写并用连字符分隔。就个人而言,我觉得这在视觉上非常吸引人,并认为它适合全小写(尽管没有连字符)的HTML

回答by user193130

Perhaps a key reason why the HTML/CSS community aligned itself with dashes instead of underscores is due to historical deficiencies in specs and browser implementations.

HTML/CSS 社区使用破折号而不是下划线的一个关键原因可能是由于规范和浏览器实现的历史缺陷。

From a Mozilla doc published March 2001 @ https://developer.mozilla.org/en-US/docs/Underscores_in_class_and_ID_Names

来自 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.

1996 年以最终形式发布的 CSS1 规范不允许在类和 ID 名称中使用下划线,除非它们被“转义”。转义的下划线看起来像这样:

    p.urgent\_note {color: maroon;}

然而,当时浏览器并没有很好地支持这种做法,而且这种做法从未流行起来。1998 年发布的 CSS2 也禁止在类和 ID 名称中使用下划线。但是,2001 年初发布的规范勘误表首次使下划线合法。不幸的是,这使本已复杂的情况变得复杂。

I generally like underscores but the backslash just makes it ugly beyond hope, not to mention the scarce support at the time. I can understand why developers avoided it like the plague. Of course, we don't need the backslash nowadays, but the dash-etiquette has already been firmly established.

我通常喜欢下划线,但反斜杠只会让它丑陋不堪,更不用说当时稀缺的支持了。我可以理解为什么开发人员像瘟疫一样避免它。当然,我们现在不需要反斜杠,但破折号礼仪已经牢固确立。

回答by Mason G. Zhwiti

I don't think anyone can answer this definitively, but here are my educated guesses:

我认为没有人可以明确回答这个问题,但这是我有根据的猜测:

  1. Underscores require hitting the Shift key, and are therefore harder to type.

  2. CSS selectors which are part of the official CSS specifications use dashes (such as pseudo-classes like :first-child and pseudo-elements :first-line), not underscores. Same thing for properties, e.g. text-decoration, background-color, etc. Programmers are creatures of habit. It makes sense that they would follow the standard's style if there's no good reason not to.

  3. This one is further out on the ledge, but... Whether it's myth or fact, there is a longstanding idea that Google treats words separated by underscores as a single word, and words separated by dashes as separate words. (Matt Cutts on Underscores vs. Dashes.)For this reason, I know that my preference now for creating page URLs is to use-words-with-dashes, and for me at least, this has bled into my naming conventions for other things, like CSS selectors.

  1. 下划线需要按 Shift 键,因此更难输入。

  2. 作为官方 CSS 规范一部分的 CSS 选择器使用破折号(例如 :first-child 和伪元素 :first-line 等伪类),而不是下划线。属性也是如此,例如文本装饰、背景颜色等。程序员是习惯的产物。如果没有充分的理由,他们会遵循标准的风格是有道理的。

  3. 这个在壁架上更远,但是......无论是神话还是事实,长期以来都有一个想法,即谷歌将下划线分隔的单词视为一个单词,将破折号分隔的单词视为单独的单词。(Matt Cutts on Underscores vs. Dashes。)出于这个原因,我知道我现在创建页面 URL 的偏好是使用带破折号的单词,至少对我来说,这已经融入了我对其他事物的命名约定,就像 CSS 选择器一样。

回答by Faust

There's been a clear uptick in hyphen-separated, whole-word segments of URLs over recent years. This is encouraged by SEO best practices. Google explicitly "recommend that you use hyphens (-) instead of underscores (_) in your URLs": http://www.google.com/support/webmasters/bin/answer.py?answer=76329.

近年来,以连字符分隔的 URL 全词段明显增加。这受到 SEO 最佳实践的鼓励。Google 明确“建议您在网址中使用连字符 (-) 而不是下划线 (_)”:http: //www.google.com/support/webmasters/bin/answer.py?answer=76329

As noted, different conventions have prevailed at different times in different contexts, but they typically are not a formal part of any protocol or framework.

如前所述,不同的约定在不同的时间在不同的环境中盛行,但它们通常不是任何协议或框架的正式组成部分。

My hypothesis, then, is that Google's position anchors this pattern within one key context (SEO), and the trend to use this pattern in class, id, and attribute names is simply the herd moving slowly in this general direction.

那么,我的假设是,Google 的位置将这种模式锚定在一个关键上下文 (SEO) 中,并且在类、ID 和属性名称中使用这种模式的趋势只是朝着这个大方向缓慢移动的群体。

回答by simhumileco

There are many reasons, but one of the most important thing is maintaining consistency.

原因有很多,但最重要的事情之一是保持一致性

I think thisarticle explains it comprehensively.

我认为这篇文章对它进行了全面的解释。

CSS is a hyphen-delimited syntax. By this I mean we write things like font-size, line-height, border-bottometc.

CSS 是一种以连字符分隔的语法。我的意思是,我们写的东西一样font-sizeline-heightborder-bottom等。

So:

所以:

You just shouldn't mix syntaxes: it's inconsistent.

你只是不应该混合语法:它是不一致的

回答by Ali Farhoudi

I think it's a programmer dependent thing. Someones like to use dashes, others use underscores.
I personally use underscores (_) because I use it in other places too. Such as:
- JavaScript variables (var my_name);
- My controller actions (public function view_detail)
Another reason that I use underscores, is this that in most IDEs two words separated by underscores are considered as 1 word. (and are possible to select with double_click).

我认为这是一个依赖于程序员的事情。有些人喜欢使用破折号,有些人喜欢使用下划线。
我个人使用下划线 ( _) 因为我在其他地方也使用它。如:
- JavaScript 变量 ( var my_name);
- 我的控制器操作 ( public function view_detail)
我使用下划线的另一个原因是,在大多数 IDE 中,由下划线分隔的两个单词被视为 1 个单词。(并且可以使用 double_click 进行选择)。