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

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

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

Is there a right answer to this?

This question is related to html css naming-conventions standards

The answer is


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.

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

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

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.


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.

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.


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.

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

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

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.

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)

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.

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.

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

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


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 .


tl;dr;

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.


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_name or #unknownName in your CSS file, you know you need to figure out what that's actually referring to.


UPDATE 2019

(Hyphens are called 'kebab-case', underscores are called 'snake_case', and then you have '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+D in 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.

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

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

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.


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

Using keyboard shortcuts like option + left/right (or ctrl+left/right on 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.


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to naming-conventions

How to name Dockerfiles What is the difference between .yaml and .yml extension? Is there a naming convention for git repositories? What's the name for hyphen-separated case? Should I use "camel case" or underscores in python? Is there a naming convention for MySQL? What is the javascript filename naming convention? REST URI convention - Singular or plural name of resource while creating it What is the standard naming convention for html/css ids and classes? What are naming conventions for MongoDB?

Examples related to standards

What are the new features in C++17? Does JSON syntax allow duplicate keys in an object? Use CSS to automatically add 'required field' asterisk to form inputs Is unsigned integer subtraction defined behavior? What is the standard naming convention for html/css ids and classes? Spaces in URLs? Is an anchor tag without the href attribute safe? Set element width or height in Standards Mode What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__? What is the proper declaration of main in C++?