ID、类和包含元素类型前缀的 HTML 命名约定?

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

HTML naming conventions for ID, class and to include element type prefix?

htmlcssxhtmlnaming-conventions

提问by mark smith

Does anyone know of a good resource to explain good naming conventions for HTML ID and classes and whether to prefix with IDs with an element type i.e. btn or button or similar?

有没有人知道一个很好的资源来解释 HTML ID 和类的良好命名约定,以及是否以元素类型(即 btn 或按钮或类似的)为 ID 加上前缀?

Should classes be plural or singular? I get that IDs should be singular due to them being unique, but what about classes?

类应该是复数还是单数?我知道 ID 应该是单一的,因为它们是唯一的,但是类呢?

IDs and classes should use nouns, right?

ID 和类应该使用名词,对吗?

I am using pages that inject other pages in the existing pages, kind of like partial pages ... hence... I was wondering if anybody as prefixed a name in front of IDs and/or classes .. kind of like a namespace or similar?

我正在使用在现有页面中注入其他页面的页面,有点像部分页面......因此......我想知道是否有人在 ID 和/或类前面加上了一个名称......有点像命名空间或相似的?

Any comments or insights really appreciated.

任何评论或见解真的很感激。

采纳答案by alex

I wouldn't prefix with the type, as you can infer this in the selector if you must

我不会在类型前加上前缀,因为如果必须,您可以在选择器中推断出这一点

form#contact {
    property: value;

}

The method you described is known as Hungarian notation, and isn't very popular.

您描述的方法称为匈牙利表示法,并不是很流行。

For what you mention, you could place your injected HTML inside one div with one unique class/id, which has a sort of localised reset. Look up CSS selector specificty to ensure your rules will take affect and not other rules in the host page's CSS. See this answer to a similar question regarding styling an element within a parent page.

对于您提到的内容,您可以将注入的 HTML 放在一个具有唯一类/ID 的 div 中,该类具有一种本地化重置。查看 CSS 选择器特性以确保您的规则生效,而不是主机页面 CSS 中的其他规则。请参阅有关在父页面中设置元素样式的类似问题的答案。

回答by Adrien Be

2015: a fresh answer focusing on existing CSS & HTML naming systems

2015:关注现有 CSS 和 HTML 命名系统的新答案

For any convention you choose, I'd suggest you pick requirements that targets your project's needs.

对于您选择的任何约定,我建议您选择针对您的项目需求的需求。

Namely: is your project small or huge? is your project going to be reused or need to handle some kind of theming? Are the devs working on the CSS/HTML keen or experienced-enough to stick with conventions? & so on..

即:您的项目是小还是大?您的项目将被重用还是需要处理某种主题?致力于 CSS/HTML 的开发人员是否热衷于或经验丰富——是否足以遵守约定?& 很快..



First, if you are not aware of this common (good?) practice: avoid IDs as styling hooks, try to only use Classes

首先,如果您不知道这种常见的(好的?)做法:避免将 ID 作为样式挂钩,尝试只使用类

Because:

因为:

  • only very few blocks (ie. page-header, page-footer) can 100% garantee the fact that they will not be reused elsewhere

  • you want to keep specificity low, there will always be times you need to override it (without using an extra ID selector or !important)

  • 只有很少的块(即页眉、页脚)可以 100% 保证它们不会在其他地方重用

  • 你想保持低特异性,总会有一些时候你需要覆盖它(不使用额外的 ID 选择器或 !important)



Common requirements/conventions:

常见要求/约定:

  • Names should be intuitive/meaningfull
  • Do NOT abbreviate names unless its a really well known abbreviation (ie. msg for Message, accnt for account)
  • Use known/common names: .site-nav, .aside-nav, .global-head, .btn-primary, .btn-secondary
  • Allow structural hierarchy (ie. BEM convention)
  • Use -or _in namings: probably subjective (devs' opinions) & depending on the keyboard languages used. Note that camelCase has been left aside for browser-compatibility issues I believe, although I never found a proof for this.
  • Never use elements in selectors unless exceptional case: this allows for more flexibility, ie. you have buttons you created using <input type="button"></input>and you want to switch to using <button></button>, if you used element types in some selectors then you can plan some annoying/time-consuming refactoring/testing/prod-bug-fixing, whereas if you use element-less selectors then the switch will be infinitely easier. SMACCS also has it in its conventions
  • For states, try to match known conventions from other languages (php, java, c#): ie, use "is-active", "is-badass", & so on
  • Name from left-to-right: from the most generic to the most precise, ie. btn-bluetheme-create-accntor accordion-modrnlook-userlist
  • a class or id name should always be specific enough to be searched across a whole project & return only the relevant results
  • Prefer direct descendant if you use descendent selectors - use .module-name > .sub-module-namevs .module-name .sub-module-name- you'll save yourself some headache in the future (simpler CSS but also more performant, although the term "CSS performance might be laughable")
  • 名称应该直观/有意义
  • 不要缩写名称,除非它是一个非常知名的缩写(即 msg 表示消息,acnt 表示帐户)
  • 使用已知/常用名称:.site-nav、.aside-nav、.global-head、.btn-primary、.btn-secondary
  • 允许结构层次(即 BEM 约定)
  • 使用-_命名:可能是主观的(开发人员的意见)并取决于所使用的键盘语言。请注意,我认为由于浏览器兼容性问题,camelCase 已被搁置一旁,尽管我从未找到证明。
  • 除非特殊情况,否则永远不要在选择器中使用元素:这允许更大的灵活性,即。你有你创建的按钮<input type="button"></input>,你想切换到 using <button></button>,如果你在一些选择器中使用了元素类型,那么你可以计划一些烦人/耗时的重构/测试/产品错误修复,而如果你使用无元素选择器那么转换将无限容易。SMACCS 在其惯例中也有它
  • 对于状态,尝试匹配来自其他语言(php、java、c#)的已知约定:即,使用“is-active”、“is-badass”等
  • 名称从左到右:从最通用到最精确,即。btn-bluetheme-create-accnt或者accordion-modrnlook-userlist
  • 类或 id 名称应始终足够具体,以便在整个项目中进行搜索并仅返回相关结果
  • 如果您使用后代选择器,则更喜欢直接后代 - 使用.module-name > .sub-module-namevs .module-name .sub-module-name- 您将来会为自己省去一些麻烦(更简单的 CSS 但也更高效,尽管术语“CSS 性能可能很可笑”)


Known conventions:

已知约定:

Structural naming convention:name element's class by describing what it is, rather than where it is or how it looks. See examples below.

结构命名约定:通过描述元素的类来命名元素的类,而不是它的位置或外观。请参阅下面的示例。

.page-container
     .page-wrap-header-n-content
     .page-header
          .branding-logo
          .branding-tagline
          .wrapper-search
          .page-nav-main
     .page-main-content
     .page-secondary-content
          .nav-supplementary
     .page-footer
          .site-info

Presentational naming convention:name element's class by describing its location and/or appearance. See examples below.

表现命名约定:通过描述元素的位置和/或外观来命名元素的类。请参阅下面的示例。

.theme-ocean-blue
.theme-apricot-orange
.skin-red-tango
.skin-darkness

Semantic naming convention:name by describing the content it enclose. As in. See examples below.

语义命名约定:通过描述它所包含的内容来命名。见下面的例子。

.product-review
.notification
.language-switch
.currency-switch
.list-of-friends
.latest-status

BEM naming convention:stands for "Block, Element, Modifier". Syntax is such as <module-name>__<sub-module-name>--<modifier-or-state>. Block is a the "main" container, a kind of module/component whatever you call it. Element is just a child component of the main component (the Block). Modifier is some kind of state. Peculiarities:the syntax (usage of dbl underscore & dbl dash), & child elements must contain their closest component's name. See examples below.

BEM 命名约定:代表“块、元素、修饰符”。语法如<module-name>__<sub-module-name>--<modifier-or-state>. Block 是一个“主”容器,无论你怎么称呼它都是一种模块/组件。元素只是主组件(块)的子组件。修饰符是某种状态。特性:语法(dbl 下划线和 dbl 破折号的使用),& 子元素必须包含它们最接近的组件的名称。请参阅下面的示例。

.nav-primary
.nav-primary__list
.nav-primary__item
.nav-primary__link
.nav-primary__link--is-active

.grid
.grid__item
.grid__description
.grid__img-wrap
.grid__img

.global-footer
.global-footer__col
.global-footer__header
.global-footer__link

OCSS naming convention:stands for Object Oriented CSS. Uses skins for branding purposes or consistency of design (ie. bg color, border color, ...). Abstracts the structural styles. Example of abstract structural style below. Two main principles of OOCSS: separate structure & skin, secondly separate container & content.

OCSS 命名约定:代表 Object Oriented CSS。将皮肤用于品牌目的或设计的一致性(即背景颜色、边框颜色等)。抽象结构样式。下面的抽象结构样式示例。OOCSS 的两个主要原则:分离结构和皮肤,其次分离容器和内容。

 .global-width {
      min-width: 780px;    /* minimum width */
      max-width: 1400px;   /* maximum width */
      margin: 0 auto;      /* Centering using margin: auto */
      position: relative;  /* Relative positioning to create a positioning context for child elements */
      padding-left: 20px;
      padding-right: 20px;
      overflow: hidden;    /* Overflow set to "hidden" for clearfixing */
 }


Some CSS guidelines:

一些 CSS 指南:

There has been a "trend" to share your CSS styleguide, here are a few you can read to pick & choose whatever seems to fit for your need (naming convention but also much more, this may be out of scope of your question):

有一种“趋势”可以分享您的 CSS 样式指南,这里有一些您可以阅读以挑选适合您需要的任何内容(命名约定还有更多,这可能超出了您的问题范围):



My biased opinion:

我的偏见:

I currently use a mix of BEM, semantic& structuralnaming conventions & it's been working out quite well.

我目前混合使用BEM语义结构命名约定,并且效果很好。

BEM& semanticworking quite well together (yes, I name my classes such as .list-of-friends__single-friend). BEM makes things especially simpler: no nesting madness in the CSS & very verbose code.

BEM语义一起工作得很好(是的,我将我的类命名为 .list-of-friends__single-friend)。BEM 使事情变得特别简单:CSS 中没有疯狂的嵌套和非常冗长的代码。

Structuralnaming convention is also welcome for the bare structure of the website, or each "template" if the website has several structures. This should, in my opinion again, be only used for very generic elements, so use carefully.

对于网站的裸结构或每个“模板”(如果网站有多个结构),也欢迎使用结构命名约定。在我看来,这应该仅用于非常通用的元素,因此请谨慎使用。

Presentationalnaming convention: really?? thanks, but no thanks. You may consider it in special cases (ie. skin a whole page in different themes).

表示命名约定:真的吗??谢谢,但不用谢。您可以在特殊情况下考虑它(即在不同主题下为整个页面设置皮肤)。

OCSSnaming convention: I have to admit, still got to look further into this. I provided links in the resources below for you to investigate further.

OCSS命名约定:我不得不承认,仍然需要进一步研究这一点。我在以下资源中提供了链接,供您进一步调查。



Resources:

资源:

回答by Ryan Florence

A lot of people don't realize you can do this stuff:

很多人没有意识到你可以做这样的事情:

.awesome {
 /* rules for anything awesome */
}

div.awesome {
 /* rules for only awesome divs */
}

button.awesome {
 /* rules for any awesome buttons, but not awesome divs */
}

div.awesome h1 {
 /* rules for H1s inside of any div.awesome */
}

div.awesome>button {
 /* rules for immediate children buttons (not grandchildren+) of div.awesomes */
}