Why do you prefer what you prefer? CSS class names: Hyphenated, camelCase or any other style?

Just wanted to hear opinions of many developers as to why they prefer to write classnames in a particular style. Here are the options:

Hyphenated: .my-first-div

Camel Case: .myFirstDiv

No style: .myfirstdiv

If I have missed any style, please mention it and explain why you use it.

PS: I don't opinions on which is better. The question is why do you prefer a particular style of writing className. :)

Mario Giambanco's photo

.class_name

I never understand why people use -'s. You can't double click on the class name and select the entire thing.

Marco Alka's photo

Hyphens work nicely as separators of parts of the name, for example

<namespace>-<block>__<element>--<modified>@<breakpoint>

However you are right, maybe I should give underscores a try for the pure part-names

Tigran Sargsyan's photo

You made me think. To highlight entire simple selector in CSS on double click, in Sublime Text, I added this:

"word_separators": "/\':,;<>~!@^&*|+{}`~?"

in "Preferences -> Settings - Syntax Specific". How did I live without this before?! :)

Adrien N.'s photo

Tough one. ๐Ÿ‘ฝ

There's a lot of writing on that and many things appeared: BEM, SMACSS, ITCSS, OCSS, Atomic CSS, ACSS...

tl;dr I don't like the BEM mixing dashes and underscores so I stick with dashes (kebab-case ๐Ÿ’ช) and have short one word component name.

In the end, that's basically mixing all good ideas up and do something like:

  • .{component} that's my basic thing & I try to have short classes names. For example: .card or .gallery ;
  • .{component}-{subcomponent} for subcomponent eg. .gallery-item or .search-filter ;
  • .{component}--{variant} for alternatives or states, for example: .card--highlight or .gallery--list or .gallery--grid or .search-filter--active
  • .js-*, for javascript selectors that are not meant to be styled but states for specific behavior (such as display: none;)

All of this, following Brad Frost's Atomic Design ๐Ÿ”ฒ which is awesome.

Also,

I know that there's a trend called "styled component" too, using style attribute and javascript and ditch almost completely css whatsoever; see the heated topic on hashnode about CSS in JS / Styled Components.

Chris DeMars's photo

I am a huge fan of BEM since it is very modular. Even though it has the potential to cause bloat in the code, classes are still easily maintainable.

Atul Sharma's photo

I personally use .my-first-div

camelcase class names make me little un-comfortable to work with

Mev-Rael's photo

Most coding styles and I prefer lisp case .my-first-div

P.S. there are also others like BEM.

Palak Bhalala's photo

Personally, I like to use Camel case or _style or no style which easier to select on double click! ;)

Marco Alka's photo

I am a huge Harry-Roberts fan, so BEM+ITCSS+namespaces+extra, hyphenated. Example:

<div class="
  o-menu__item / js-menu__item
  o-menu__icon@sd
  o-menu__item--active
"></div>