What is the standard naming convention for html/css ids and classes?
HtmlCssNaming ConventionsStandardsHtml Problem Overview
Does it depend on the platform you are using, or is there a common convention that most developers suggest/follow?
There are several options:
id="someIdentifier"'
- looks pretty consistent with javascript code.id="some-identifier"
- looks more like html5-like attributes and other things in html.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?
Html Solutions
Solution 1 - Html
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.
Solution 2 - Html
tl;dr; 2022
It seems "-" would be industry standard now.
# Deprecated
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.
Solution 3 - Html
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.
Solution 4 - Html
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.
Solution 5 - Html
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.
Solution 6 - Html
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").
Solution 7 - Html
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.