Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I name my CSS classes?

Tags:

html

css

How should my class names be?

For example, a CSS class for a vote count, how should I name it?

.vote-count-post     (1) // SO uses this
.VoteCountPost       (2)
.voteCountPost       (3)
.vote.count-post     (4)
.vote .count-post    (5)
.vote .count.post    (6)
  • What are the advantages and disadvantages of each?
  • Which is most used and why?
  • Are there any implications in any of these?
  • May I have any uppercase in my CSS?
like image 267
BrunoLM Avatar asked Jan 22 '11 15:01

BrunoLM


4 Answers

4, 5 and 6 are special

  • .vote.count-post matches elements with class="vote count-post", or class="count-post vote" or even class="vote something-else count-post".
  • .vote .count-post matches elements with class="count-post" that are subelements of an element with class="vote"
  • and .vote .count.post is a mix of those both

Between 1, 2 and 3, all that matters is preference of style. Some people prefer one over another just as they do in programming languages. So just choose whatever you personally prefer, or what is more appropriate for you.

like image 106
poke Avatar answered Oct 04 '22 20:10

poke


I vote for (1) to always use lower case for your CSS. That way you don't have to remember where you capitalize stuff. So that eliminates (2) and (3).

(5) is really two different elements so can't apply to a single element.

(4) and (6) are invalid for a single element. (4) assumes you are applying two classes to the same element such as class='vote count-post'. (6) is a combination of (4) and (5).

like image 28
Keltex Avatar answered Oct 04 '22 22:10

Keltex


It's just naming, so it's up to you what you like. Either of your examples would work fine. Just pick one and stick to it.

The three first selectors addresses single elements, the fourth addresses a single element with two classes, the fifth addresses an element inside another, and the sixth does the same but with the inner ellement having two classes.

I would probably put class="Vote" on the surronding element, and out class="count" on the count element inside it to address it. I use pascal case for surrounding elements and lowercase for child elements inside them, so I would use:

.Vote .count
like image 4
Guffa Avatar answered Oct 04 '22 21:10

Guffa


I see the first approach a lot (the jQuery UI CSS framework uses it and I find it a very good example for good CSS).

I personally don't like camelcasing in class names from (2) and (3) because it is really easy to get it wrong (just write VotecountPost and it won't work).

(4), (5), (6) are not really a convention thing but rather different selectors as others pointed out already.

like image 3
Daff Avatar answered Oct 04 '22 22:10

Daff