299

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?

Chait
  • 1,018
  • 2
  • 16
  • 27
egervari
  • 21,108
  • 30
  • 115
  • 171
  • related http://stackoverflow.com/a/23658906/759452 – Adrien Be Jun 03 '14 at 08:37
  • 1
    I found this... [HTML Naming Conventions](https://courses.cs.washington.edu/courses/cse154/17au/styleguide/html-css/naming-conventions-html.html) – Robin Hood Feb 08 '20 at 16:47
  • Apparently square brackets should not be used as a part of the id. At least bootstrap doesn't match it with a data-target if it contains any square brackets. And it cant start with a number, because it's not a valid variable name. – Vala. D. Mar 03 '21 at 12:12
  • Square brackets definitely shouldn't be used as part of the id! `the-tag.the-class#the-id[disabled][src=exactUrl][href*=partialUrl]` is a valid css selector. If the id were `id="the-id[disabled]"`, you wouldn't be able to tell whether you were selecting the element with `id="the-id[disabled]"` or `id="the-id"` and `disabled=true`. Likewise, you can't use dots in the id, or hash signs. – RoboticRenaissance May 05 '21 at 15:36

8 Answers8

314

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.

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

Update 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 you prefer, which may easily change over time.

Update 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't a standard.

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

Update 2016 (you asked for it)

I've adopted the BEM standard 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 actually a standard (so my no becomes a yes perhaps) but it's still up to you what you decide to use in a project. Most importantly: be consistent with what you choose.

Update 2019 (you asked for it)

After writing no CSS for quite a while, I started working at a place that uses OOCSS in 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.

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.

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

Update 2020

A boring update this year. I'm still using BEM. My position hasn't really changed from the 2019 update for the reasons listed above. Use what works for you that scales with your team size and hides as much or as little of CSS' poor featureset as you like.

Bojangles
  • 91,543
  • 47
  • 160
  • 197
  • 13
    I think that according as your app get bigger your ids starts to be long and complex, then in that moment the dashes doesn't look good. I'm also using Sublime and Twitter Bootstrap, and I'm agreement in use dashes for classes like Bootstrap does. But the ids is more for JavaScript, so i prefer use camelCase in that case. – glrodasz Oct 09 '13 at 08:55
  • I'm pretty much married to camelCase still. When writing Java and Javascript all day, I can't stomach doing dashes or underscores. It looks weird, and I'm more prone to creating errors. – egervari Mar 08 '14 at 02:10
  • 3
    To me I still prefer underscore style. Simply because all HTML tags and attributes are lower cases. I'm avoiding any upper case here. – yaoxing May 23 '14 at 11:04
  • 3
    One quasi-standard I've seen (Bootstrap seems to do some of this) is to prepend "js-" to any CSS classes or ids that are specifically used for Javascript. Maybe this will make the cut for 2016 :) – Dolan Antenucci Apr 02 '16 at 16:44
  • @DolanAntenucci That seems to be a pretty sensible idea, although I've started using [BEM](http://getbem.com/introduction/) which takes a similar but more generic approach (using it's Modifiers) – Bojangles Apr 04 '16 at 09:07
  • 1
    @Bojangles -- BEM looks interesting, although the usage of dashes *and* underscores for different purposes would take some getting used to; likewise, the double dashes/underscores would as well :) Thanks for sharing – Dolan Antenucci Apr 04 '16 at 13:24
  • 9
    One reason I believe people prefer dashes in CSS id's and classes are for functionality. Using **option + left/right arrow** to traverse your code word by word stops at each dash, allowing you to easily traverse the id or class name using keyboard shortcuts. Underscores and camelcase does not get picked up and the cursor will drift right over them as if it were all one single word. – Kyle Vassella Jan 09 '17 at 00:29
  • @KyleVassella Good point. I'd be interested to know if BEM's guidelines were inspired by this behaviour – Bojangles Jan 09 '17 at 10:24
  • 1
    Where are you in 2019, @Bojangles? – Adrian Wiik Aug 09 '19 at 11:26
  • 1
    @Bojangles you are an awesome guy – void Nov 12 '19 at 06:01
  • @BluePrint Thank you for your input. It's valued and truly appreciated. – Bojangles Sep 12 '20 at 10:18
  • 2
    Upvoted due to being updated each year to reflect how more things change, more they stay the same. – Mandemon Sep 25 '20 at 07:23
51

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 .

azurkin
  • 1,614
  • 2
  • 17
  • 19
34

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.

Weijing Jay Lin
  • 2,156
  • 2
  • 25
  • 38
  • 7
    Someone flagged this. Your English could be better, but assuming this is correct, it seems like a useful addition to the corpus of knowledge here, so I’ll vote against deleting it. – Tom Zych Jan 17 '16 at 11:58
  • 5
    This answer is underated! – basickarl Mar 30 '16 at 15:37
  • 24
    The workaround being `var x = document.myForm['my-Id'].value;` – Dirk Diggler Nov 22 '16 at 16:23
  • I would not use any of these methods, but rather `getElementById('whatever-you-want_my_friend')`. It depends. If your code has backend (server-side) coding rendering HTML, using camelCase to match your naming conventions, or snake_case, whatever your coding language uses, is probably the best so that searching through both your front and back end code is concordant. – Oliver Williams Mar 07 '20 at 13:06
17

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 'Title Case', 'PascalCase', and 'camelCase')

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/PascalCase.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.


UPDATE 2021

At this point in my life, I try to exclusively use kebab-case for project file names.

And a weird combination of snake_case.kebab-case.dot.case.Title.Case for files which are for human communications. Like an excel file that contains a report might be "Report_Name-Report_Type-2021.05.04_13.02" for a report generated on May Fourth at 1:02 PM. I was actually going to use Title Case in said report name, but if you resave the file, you'll get no spaces. And I was going to use kebab-case and make the datestamp iso-compliant, but the client got confused because they use American month-day-year format for dates. Another example is "SomeRequestForm-ProjectName-01.pdf".

Client-Readable stuff is hard to work around.

I avoid spaces where possible (and the client doesn't ask for them), because they're not cli-safe. I've taken up the Angular approach to filenames in projects. some-thing.type.ts, where the description is kebab-case, and the standard type of object stored in the file is separated with dots like the extension. I don't typically do some-area_some-thing.type.ts, unless the file is standalone and portable. If it's in a project, then I just use folders like some-area/some-thing.type.ts

Additionally, I use kebab-case for css classes and I sometimes mix snakeAndCamel_case for html ids, but typically I no longer use html ids, because I work with reusable components, and that breaks. When I do use ids, it's typically something like someComponent-someElement_49bea6c9-551b-400a-a3e0-59ed40967646 where that uuid is a generated uuid self-assigned by each component instance. This is not supported in Angular, so I tend to come up with other workarounds, such as keeping the entire form input inside the label.

Additionally, for variable names, I still use mostly camelCase, except for class names and sometimes function names. When working with an external package, I just do what they're doing. For things that mimic environment variables, I do use ALL_CAPS_SNAKE_CASE, this includes node.js process.env.SOME_ENV_VAR and combinedConfiguration.SOME_ENV_VAR (for when I'm overriding process.env with a parameter config)

My tl;dr; still applies a few years later. There is no one true answer. But try to keep one style per project. And lower the number of words in your symbols wherever possible.

RoboticRenaissance
  • 845
  • 1
  • 10
  • 15
  • same as my preference. camelCase for variables and under_score for id, however, I normally apply under_scores for both classes and names too. – Vincent Edward Gedaria Binua Aug 20 '17 at 17:19
  • I Liked because it's the same like I prefer to use. 'snake_case' for ids, 'kebab-case' for css, 'camelCase' for functions and variables. – Eduardo Paz Jun 21 '20 at 10:37
  • 1
    What you list as Pascal case is actually camel case. Pascal case capitalizes the first letter in every word (what you called Title case), whereas camel case doesn't capitalize the first letter of the first word, creating a hump in the middle. 'PascalCase', 'camelCase' – deathwombat Apr 30 '21 at 08:39
  • You are so very right @deathwombat, I think I made a typo. – RoboticRenaissance May 05 '21 at 14:57
11

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.
tim-montague
  • 12,048
  • 2
  • 50
  • 40
4

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.

Kyle Vassella
  • 1,329
  • 4
  • 20
  • 43
  • Just so others don't get confused: For Windows it is CTRL + LEFT / RIGHT – Gordon Mohrin Feb 21 '17 at 06:06
  • That's actually my biggest reason for using underscores or camelCase instead of dashes where possible. `the-red-box` is impossible to select with a simple double click or two key presses. Also cmd/ctrl + D for vsCode. Instead you have to go multiple times or drag-select with the mouse. But `the_red_box` supports all three easy-select shortcuts. – RoboticRenaissance Dec 27 '19 at 21:03
1

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

mkdrive2
  • 229
  • 1
  • 12
  • The link for "Best Naming Practises" just says there is no convention, just be consistent. BTW w3schools is not related to the W3C. – run_the_race Oct 09 '20 at 08:45
1

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.

Louise Eggleton
  • 807
  • 1
  • 12
  • 24