html/css id 和类的标准命名约定是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6028211/
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 08:38:02  来源:igfitidea点击:

What is the standard naming convention for html/css ids and classes?

htmlcssnaming-conventionsstandards

提问by egervari

Does it depend on the platform you are using, or is there a common convention that most developers suggest/follow?

它取决于您使用的平台,还是大多数开发人员建议/遵循的通用约定?

There are several options:

有几种选择:

  1. id="someIdentifier"'- looks pretty consistent with javascript code.
  2. id="some-identifier"- looks more like html5-like attributes and other things in html.
  3. id="some_identifier"- looks pretty consistent with ruby code and is still a valid identifier inside of Javascript
  1. id="someIdentifier"'- 看起来与 javascript 代码非常一致。
  2. id="some-identifier"- 看起来更像 html5-like 属性和 html 中的其他东西。
  3. id="some_identifier"- 看起来与 ruby​​ 代码非常一致,并且仍然是 Javascript 中的有效标识符

I was thinking #1 and #3 above make the most sense because they play nicer with Javascript.

我认为上面的 #1 和 #3 最有意义,因为它们与 Javascript 一起玩得更好。

Is there a right answer to this?

对此有正确的答案吗?

采纳答案by Bojangles

There isn't one.

没有一个。

I use underscores all the time, due to hyphens messing up the syntax highlighting of my text editor (Gedit), but that's personal preference.

我一直使用下划线,因为连字符弄乱了我的文本编辑器 (Gedit) 的语法突出显示,但这是个人喜好。

I've seen all these conventions used all over the place. Use the one that you think is best - the one that looks nicest/easiest to read for you, as well as easiest to type because you'll be using it a lot. For example, if you've got your underscore key on the underside of the keyboard (unlikely, but entirely possible), then stick to hyphens. Just go with what is best for yourself. Additionally, all 3 of these conventions are easily readable. If you're working in a team, remember to keep with the team-specified convention (if any).

我已经看到所有这些约定在各地使用。使用您认为最好的一种 - 对您来说看起来最好/最容易阅读的一种,以及最容易打字的一种,因为您会经常使用它。例如,如果您的下划线键位于键盘底部(不太可能,但完全有可能),那么请坚持使用连字符。只选择最适合自己的。此外,所有这 3 个约定都很容易阅读。如果您在团队中工作,请记住遵守团队指定的约定(如果有)。

Update 2012

2012 年更新

I've changed how I program over time. I now use camel case (thisIsASelector) instead of hyphens now; I find the latter rather ugly. Use whatever youprefer, which may easily change over time.

随着时间的推移,我改变了我的编程方式。我现在使用驼峰式 ( thisIsASelector) 而不是连字符;我觉得后者相当丑陋。使用喜欢的任何东西,这可能会随着时间的推移而轻松改变。

Update 2013

2013 年更新

It looks like I like to mix things up yearly... After switching to Sublime Text and using Bootstrap for a while, I've gone back to dashes. To me now they look a lot cleaner than un_der_scores or camelCase. My original point still stands though: there isn'ta standard.

看起来我每年都喜欢把事情混在一起……在切换到 Sublime Text 并使用 Bootstrap 一段时间后,我又回到了破折号。现在对我来说,它们看起来比 un_der_scores 或camelCase 干净得多。不过,我的原点仍然成立:没有标准。

Update 2015

2015 年更新

An interesting corner case with conventions here is Rust. I really like the language, but the compiler will warn you if you define stuff using anything other than underscore_case. You can turn the warning off, but it's interesting the compiler strongly suggests a convention by default. I imagine in larger projects it leads to cleaner code which is no bad thing.

一个有趣的带有约定的角落案例是Rust。我真的很喜欢这种语言,但是如果您使用underscore_case. 您可以关闭警告,但有趣的是编译器在默认情况下强烈建议使用约定。我想在更大的项目中它会导致更清晰的代码,这并不是一件坏事。

Update 2016(youasked for it)

2016 年更新要求的)

I've adopted the BEMstandard for my projects going forward. The class names end up being quite verbose, but I think it gives good structure and reusability to the classes and CSS that goes with them. I suppose BEM is actuallya standard (so my nobecomes a yesperhaps) but it's still up to you what you decide to use in a project. Most importantly: be consistent with what you choose.

我已经为我的项目采用了BEM标准。类名最终变得非常冗长,但我认为它为类和 CSS 提供了良好的结构和可重用性。我认为 BEM实际上是一个标准(所以我可能no会成为一个标准yes),但您决定在项目中使用什么仍然取决于您。最重要的是:与您的选择保持一致。

Update 2019(youasked for it)

2019 年更新要求的)

After writing no CSS for quite a while, I started working at a place that uses OOCSSin one of their products. I personally find it pretty unpleasant to litter classes everywhere, but not having to jump between HTML and CSS all the time feels quite productive.

在很长一段时间没有写 CSS 之后,我开始在一个在他们的一个产品中使用OOCSS的地方工作。我个人觉得到处乱扔类是很不愉快的,但不必一直在 HTML 和 CSS 之间跳转感觉非常有效率。

I'm still settled on BEM, though. It's verbose, but the namespacing makes working with it in React components very natural. It's also great for selecting specific elements when browser testing.

不过,我仍然选择 BEM。它很冗长,但命名空间使得在 React 组件中使用它非常自然。它也非常适合在浏览器测试时选择特定元素。

OOCSS and BEM are just some of the CSS standards out there. Pick one that works for you - they're all full of compromised because CSS just isn't that good.

OOCSS 和 BEM 只是现有的一些 CSS 标准。选择一个适合你的——它们都充满了妥协,因为 CSS不是那么好

回答by azurkin

There is css&html style guide by google, which recommends to always use a hyphen: https://google.github.io/styleguide/htmlcssguide.html#ID_and_Class_Name_Delimiters.

google 提供了 css&html 样式指南,建议始终使用连字符:https: //google.github.io/styleguide/htmlcssguide.html#ID_and_Class_Name_Delimiters

回答by Weijing Jay Lin

I suggest you use an underscore instead of a hyphen (-), since ...

我建议您使用下划线而不是连字符 (-),因为 ...

<form name="myForm">
  <input name="myInput" id="my-Id" value="myValue"/>
</form>

<script>
  var x = document.myForm.my-Id.value;
  alert(x);
</script>

you can access the value by id easily in like that. But if you use a hyphen it will cause a syntax error.

您可以像这样轻松地通过 id 访问该值。但如果使用连字符,则会导致语法错误。

This is an old sample, but it can work without jquery -:)

这是一个旧示例,但它可以在没有 jquery 的情况下工作-:)

thanks to @jean_ralphio, there is work around way to avoid by

感谢@jean_ralphio,有办法避免

var x = document.myForm['my-Id'].value;

Dash-style would be a google code style, but I don't really like it. I would prefer TitleCase for id and camelCase for class.

Dash 样式将是一种 google 代码样式,但我真的不喜欢它。我更喜欢 TitleCase 为 id 和 camelCase 为类。

回答by RoboticRenaissance

tl;dr;

tl;博士;

There is no one true answer. You can pick one of the many out there, or create your own standards based on what makes sense, depending upon who you're working with. And it is 100% dependent upon the platform.

没有一个真正的答案。您可以从众多选择中选择一个,或者根据与您合作的人的合理性来创建自己的标准。它 100% 依赖于平台。



Original Post

原帖

Just one more alternative standard to consider:

还有一个可供考虑的替代标准:

<div id="id_name" class="class-name"></div>

And in your script:

在你的脚本中:

var variableName = $("#id_name .class-name");

This just uses a camelCase, under_score, and hyphen-ation respectively for variables, ids, and classes. I've read about this standard on a couple of different websites. Although a little redundant in css/jquery selectors, redundancies make it easier to catch errors. eg: If you see .unknown_nameor #unknownNamein your CSS file, you know you need to figure out what that's actually referring to.

这仅对变量、ID 和类分别使用驼峰式、下划线和连字符。我已经在几个不同的网站上阅读了有关此标准的信息。尽管在 css/jquery 选择器中有点多余,但冗余使捕获错误更容易。例如:如果您看到.unknown_name#unknownName在您的 CSS 文件中,您知道您需要弄清楚它实际指的是什么。



UPDATE 2019

2019 年更新

(Hyphens are called 'kebab-case', underscores are called 'snake_case', and then you have 'TitleCase', 'pascalCase')

(连字符称为“kebab-case”,下划线称为“snake_case”,然后是“TitleCase”、“pascalCase”)

I personally dislike hyphens. I originally posted this as one alternative (because the rules are simple). However, Hyphens make selection shortcuts very difficult (double click, ctrl/option+ left/right, and ctrl/cmd+Din vsCode. Also, class names and file names are the only place where hyphens work, because they're almost always in quotes or in css, etc. But the shortcut thing still applies.

我个人不喜欢连字符。我最初将其作为一种替代方法发布(因为规则很简单)。但是,连字符使选择快捷方式变得非常困难(在 vsCode 中双击、ctrl/ option+ left/rightctrl/ cmd+ D。此外,类名和文件名是唯一可以使用连字符的地方,因为它们几乎总是在引号中或在 css 中,等等. 但捷径的东西仍然适用。

In addition to variables, class names, and ids, you also want to look at file name conventions. And Git Branches.

除了变量、类名和 id,您还需要查看文件名约定。和 Git 分支。

My office's coding group actually had a meeting a month or two ago to discuss how we were going to name things. For git branches, we couldn't decide between 321-the_issue_description or 321_the-issue-description. (I wanted 321_theIssueDescription, but my coworkers didn't like that.)

我办公室的编码小组实际上在一两个月前召开了一次会议,讨论我们将如何命名事物。对于 git 分支,我们无法在 321-the_issue_description 或 321_the-issue-description 之间做出决定。(我想要 321_theIssueDescription,但我的同事不喜欢那样。)

An Example, to demonstrate working with other peoples' standards...

一个例子,展示与其他人的标准一起工作......

Vue.js does have a standard. Actually they have two alternate standards for several of their items. I dislike both of their versions for filenames. They recommend either "/path/kebab-case.vue"or "/path/TitleCase.Vue". The former is harder to rename, unless you're specifically trying to rename part of it. The latter is not good for cross-platform compatibility. I would prefer "/path/snake_case.vue". However, when working with other people or existing projects, it's important to follow whatever standard was already laid out. Therefore I go with kebab-case for filenames in Vue, even though I'll totally complain about it. Because not following that means changing a lot of files that vue-cli sets up.

Vue.js 确实有一个标准。实际上,他们的几个项目有两个替代标准。我不喜欢他们两个版本的文件名。他们推荐"/path/kebab-case.vue""/path/TitleCase.Vue"。前者更难重命名,除非您专门尝试重命名其中的一部分。后者不利于跨平台兼容性。我宁愿"/path/snake_case.vue". 但是,在与其他人或现有项目合作时,遵循已经制定的任何标准很重要。因此,我在 Vue 中使用 kebab-case 作为文件名,即使我会完全抱怨它。因为不遵循这意味着更改 vue-cli 设置的许多文件。

回答by tfmontague

There is no agreed upon naming convention for HTML and CSS. But you could structure your nomenclature around object design. More specifically what I call Ownership and Relationship.

HTML 和 CSS 的命名约定尚未达成一致。但是您可以围绕对象设计构建您的命名法。更具体地说,我称之为所有权和关系。

Ownership

所有权

Keywords that describe the object, could be separated by hyphens.

描述对象的关键字可以用连字符分隔。

car-new-turned-right

汽车新右转

Keywords that describe the object can also fall into four categories (which should be ordered from left to right): Object, Object-Descriptor, Action, and Action-Descriptor.

描述对象的关键字也可以分为四类(应该从左到右排序):对象、对象-描述符、动作和动作-描述符。

car - a noun, and an object
new - an adjective, and an object-descriptor that describes the object in more detail
turned - a verb, and an action that belongs to the object
right - an adjective, and an action-descriptor that describes the action in more detail

car - 一个名词,一个宾语
new - 一个形容词和一个更详细描述宾语
的宾语
叙词更详细的动作

Note: verbs (actions) should be in past-tense (turned, did, ran, etc).

注意:动词(动作)应该是过去时(turned、did、run 等)。

Relationship

关系

Objects can also have relationships like parent and child. The Action and Action-Descriptor belongs to the parent object, they don't belong to the child object. For relationships between objects you could use an underscore.

对象也可以有父子关系。Action 和 Action-Descriptor 属于父对象,它们不属于子对象。对于对象之间的关系,您可以使用下划线。

car-new-turned-right_wheel-left-turned-left

  • car-new-turned-right (follows the ownership rule)
  • wheel-left-turned-left (follows the ownership rule)
  • car-new-turned-right_wheel-left-turned-left (follows the relationship rule)

汽车新右转左轮左转左

  • car-new-turned-right(遵循所有权规则)
  • 左轮左转(遵循所有权规则)
  • car-new-turned-right_wheel-left-turned-left(遵循关系规则)

Final notes:

最后说明:

  • Because CSS is case-insensitive, it's better to write all names in lower-case (or upper-case); avoid camel-case or pascal-case as they can lead to ambiguous names.
  • Know when to use a class and when to use an id. It's not just about an id being used once on the web page. Most of the time, you want to use a class and not an id. Web components like (buttons, forms, panels, ...etc) should always use a class. Id's can easily lead to naming conflicts, and should be used sparingly for namespacing your markup. The above concepts of ownership and relationship apply to naming both classes and ids, and will help you avoid naming conflicts.
  • If you don't like my CSS naming convention, there are several others as well: Structural naming convention, Presentational naming convention, Semantic naming convention, BEM naming convention, OCSS naming convention, etc.
  • 因为 CSS 不区分大小写,所以最好将所有名称都写成小写(或大写);避免使用驼峰式大小写或帕斯卡式大小写,因为它们会导致名称不明确。
  • 知道何时使用类以及何时使用 id。这不仅仅是关于在网页上使用一次的 id。大多数时候,你想使用一个类而不是一个 id。像(按钮、表单、面板等)这样的 Web 组件应该总是使用一个类。Id 很容易导致命名冲突,应该谨慎使用命名空间标记。上述所有权和关系概念适用于命名类和 ID,并将帮助您避免命名冲突。
  • 如果你不喜欢我的 CSS 命名约定,还有其他几个:结构命名约定、展示命名约定、语义命名约定、BEM 命名约定、OCSS 命名约定等。

回答by Kyle Vassella

Another reason why many prefer hyphens in CSS id and class names is functionality.

许多人更喜欢 CSS id 和类名中的连字符的另一个原因是功能。

Using keyboard shortcuts like option+ left/right(or ctrl+left/righton Windows) to traverse code word by word stops the cursor at each dash, allowing you to precisely traverse the id or class name using keyboard shortcuts. Underscores and camelCase do not get detected and the cursor will drift right over them as if it were all one single word.

使用诸如option+ left/ right(或Windows 上的ctrl+ left/ right)之类的键盘快捷键逐字遍历代码会使光标停在每个破折号处,从而允许您使用键盘快捷键精确遍历 id 或类名称。下划线和驼峰式大小写不会被检测到,光标会在它们上方漂移,就好像它们都是一个单词一样。

回答by Louise Eggleton

I think it is platform dependent. When developing in .Net MVC, I use bootstrap style lower case and hyphens for class names, but for ids I use PascalCase.

我认为它依赖于平台。在 .Net MVC 中开发时,我使用 bootstrap 风格的小写和连字符作为类名,但对于 id,我使用 PascalCase。

The reasoning for this is that my views are backed by strongly typed view models. Properties of C# models are pascal case. For the sake of model binding with MVC it makes sense that the names of HTML elements that bind to the model are consistent with the view model properties which are pascal case. For simplicity my ids are use the same naming convention as element names except for radio buttons and check boxes which require unique ids for each element in the named input group.

这样做的原因是我的视图由强类型视图模型支持。C# 模型的属性是 pascal case。为了与MVC进行模型绑定,绑定到模型的HTML元素的名称与pascal大小写的视图模型属性一致是有意义的。为简单起见,我的 id 使用与元素名称相同的命名约定,但单选按钮和复选框需要命名输入组中的每个元素的唯一 id。

回答by mkdrive2

I just recently started learning XML. The underscore version helps me separate everything XML-related (DOM, XSD, etc.) from programming languages like Java, JavaScript (camel case). And I agree with you that using identifiers which are allowed in programming languages looks better.

我最近才开始学习 XML。下划线版本帮助我将所有与 XML 相关的(DOM、XSD 等)与 Java、JavaScript(驼峰式案例)等编程语言分开。我同意你的看法,使用编程语言中允许的标识符看起来更好。

Edit: Might be unrelated, but here is a link for rules and recommendations on naming XML elements which I follow when naming ids (sections "XML Naming Rules" and "Best Naming Practices").

编辑:可能不相关,但这里有一个关于命名 XML 元素的规则和建议的链接,我在命名 id 时遵循这些规则和建议(“XML 命名规则”和“最佳命名实践”部分)。

http://www.w3schools.com/xml/xml_elements.asp

http://www.w3schools.com/xml/xml_elements.asp