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

发布于 2024-12-06 18:14:25 字数 2041 浏览 0 评论 0 原文

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

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

代码完成和破折号。编辑

大多数编辑器将破折号视为单词分隔符,因此我无法通过 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 中为变量编写 underscored_names。这很方便且一致,但为了“适应”,我现在使用:

  • dash-case in HTML/CSS
  • camelCase in JavaScript
  • underscore_case > 在 PHP 和 ruby​​ 中

这并没有让我太困扰,但我想知道为什么它们变得如此不一致,似乎是故意的。至少使用下划线可以保持一致性:

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

这些差异造成了我们必须 不必要地翻译字符串,并且可能存在错误。

所以我问:为什么社区几乎普遍选择破折号,有什么理由比下划线更重要吗?

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

In the past I've always used underscores for defining class and id attributes 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.

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".

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

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.)

Ambiguity with arithmetic operator

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

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 Compass framework) 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:

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

Inconsistency with variable naming across languages

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

  • dash-case in HTML/CSS
  • camelCase in JavaScript
  • underscore_case in PHP and 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 strings unnecessarily, 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 question from back around the time this started, but I'm of the opinion that it's not (or shouldn't have 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

夏末的微笑 2024-12-13 18:14:25

代码完成

我猜破折号是否被解释为标点符号或不透明标识符取决于所选择的编辑器。然而,作为个人喜好,我更喜欢能够在 CSS 文件中的每个单词之间进行制表符,并且如果它们用下划线分隔并且没有停止符,我会发现它很烦人。

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

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

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

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

算术运算符的歧义

我想说,通过 JavaScript 中的点表示法访问 HTML 元素是一种漏洞而不是一个功能。从早期糟糕的 JavaScript 实现来看,这是一个糟糕的构造,实际上并不是一个很好的实践。对于现在使用 JavaScript 执行的大部分操作,您需要使用 CSS 选择器< /a> 无论如何都会从 DOM 中获取元素,这使得整个点表示法毫无用处。您更喜欢哪一个?

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

我发现前两个选项更可取,特别是因为 '#first-name' 可以用 JavaScript 变量替换并动态构建。我还发现它们更悦目。

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

跨语言的变量命名不一致

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

一般来说,您会发现采用感觉和看起来最适合您所编写的语言的风格比尝试将自己的风格硬塞到每种不同的语言中要好。由于您无法避免使用本机库和语言构造,因此无论您是否喜欢,您的风格都会被本机风格“污染”,因此尝试几乎是徒劳的。

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

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.

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:

<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 Selectors for fetching elements from the DOM anyway, which makes the whole dot notation rather useless. Which one would you prefer?

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.

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 calc function, which goes to show that in CSS itself, this isn't an issue.

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. XSLT uses lower-case with hyphen delimiters and XML Schema uses camel-casing.

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.

美人骨 2024-12-13 18:14:25

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

来自 2001 年 3 月发布的 Mozilla 文档 @ https://developer.mozilla.org/en-US /docs/Underscores_in_class_and_ID_Names

CSS1 规范于 1996 年发布其最终版本,但并未
允许在类和 ID 名称中使用下划线,除非它们
被“逃脱”了。转义下划线看起来像这样:

 p.urgent\_note {颜色:栗色;}

然而,当时的浏览器并没有很好地支持这一点
实践从未流行起来。 1998 年发布的 CSS2 也禁止
在类和 ID 名称中使用下划线。然而,勘误表
2001 年初发布的规范强调了
第一次。不幸的是,这使本来就复杂的事情变得复杂起来
风景。

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

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.

From a Mozilla doc published March 2001 @ 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.

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.

夏日落 2024-12-13 18:14:25

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

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

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

  3. 这个问题还很遥远,但是......无论是神话还是事实,长期以来都有一个想法,即谷歌将由下划线分隔的单词视为单个单词,将由破折号分隔的单词视为单独的单词。 (Matt Cutts 论下划线与破折号。) 出于这个原因,我知道我现在创建页面 URL 的偏好是使用单词和破折号,至少对我来说,这已经渗透到我对其他事物的命名约定中,比如 CSS 选择器。

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.

梦屿孤独相伴 2024-12-13 18:14:25

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

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

CSS 是连字符分隔的语法。我的意思是我们编写诸如 font-sizeline-heightborder-bottom 等内容。

所以:

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

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

I think this article explains it comprehensively.

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

So:

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

小清晰的声音 2024-12-13 18:14:25

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

如上所述,不同的公约在不同的时间、不同的背景下盛行,但它们通常不是任何协议或框架的正式组成部分。

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

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.

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.

安稳善良 2024-12-13 18:14:25

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

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).

梦中楼上月下 2024-12-13 18:14:25

正如一些答案所说的 SEO 点,特别是 Google,值得一提的是,当使用多个单词作为类名时,Google 本身使用下划线 (_)。

输入图片此处描述

as some answers say the SEO point, specifically Google, it worthies mentioning that Google itself uses underscore (_) when it comes using more than word for a class name.

enter image description here

暖伴 2024-12-13 18:14:25
point of refactoring only btn to bt

case: btn_pink
search btn in word
result btn

case: btn-pink
search btn in word
result btn | btn-pink

case: btn-pink
search btn in regexp
\bbtn\b(?!-) type to hard
result btn
point of refactoring only btn to bt

case: btn_pink
search btn in word
result btn

case: btn-pink
search btn in word
result btn | btn-pink

case: btn-pink
search btn in regexp
\bbtn\b(?!-) type to hard
result btn
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文