views:

216

answers:

6

What are the best practices when naming CSS selectors?

SomeContainerContent
some_container_content
some-container-content

I read the other similar questions here on stack overflow, but there is no general consensus in the answers. I was wondering if anyone else had more to add.

+1  A: 

I really think that it is up to you. However, what is important is to be consistent. For example, I like to use underscores for ids and dashes for classes.

Randy Simon
...that actually sounds kinda inconsistent for me, since my brain groups CSS as all one thing. Is that to keep classes and IDs separate, as far as mental storage goes?
Matchu
A: 

It really does not matter and comes down to your personal taste. However, for a project it should be consistent! So, if there is already a css present, go for the style set by this style.

Obalix
A: 

I use dashes (-) for everything HTML/CSS and underscores for PHP variables. Keeps things organised for me.

Tom
A: 

I use dashes. Probably because lots of things on the web are case sensitive and I'm in a habit of using all lowercase for file names and such already when working on the web. Underscores are hard to see when underlined, so I shy away from them as well.

Seems most people CamelCase though:

poll on what people use

Austin Fitzpatrick
That's an interesting link, thank you for sharing. CamelCase is the most confusing to me, as I'm used to ruby class names in CamelCase.
deb
+3  A: 

The general thought is to use hyphens. There are, in fact, potential compatibility issues with other options.

  • Underscores are not allowed in class names or IDs in certain (granted, old, NS4-type) browsers.
  • The CSS spec does not specify how browsers should handle case, so using camelCase leaves one open to ambiguous interpretation.

Additionally, CSS uses hyphens internally for things like first-child.

Though the compatibility issues are generally a non-issue in modern browsers, that's how the standard came about, and I recommend sticking with it. You'd be fine if you were to deviate, but why bother?

Matchu
Good points.Also, I can't use hyphens in variable names and in helper methods in rails, which adds another clue to distinguish css classes if I keep them hyphened.
deb
A: 

"In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F"."

alexnexus