Best practice for CSS class naming for use with jQuery selectors

While building a Javascript-heavy web application, what is the best practice for naming CSS classes to keep the Javascript code and CSS stylesheets clean and the UI structure flexible?


Option 1: Name every single element uniquely.

For example,

// HTML
<div id="list">
  <button class="list-delete" />
  <div class="list-items">
    <div class="item">
      <button class="item-delete" />
      <h1 class="item-name">Item 1</h1>
    </div>
  </div>
</div>

// CSS
.list-delete {
  color: black;
}

.item-delete {
  color: blue;
}

// Javascript
$(".list-delete").show();
$(".item-delete").hide();

Pros:

  • Selecting an item for styling or JS manipulation is easy

Cons:

  • Element names start becoming really long and hard to keep track of
  • Changing the HTML structure requires lots of renaming

Option 2: Name every element semantically, and select elements hierarchically.

For example,

// HTML
<div id="list">
  <button class="delete" />
  <div class="items">
    <div class="item">
      <button class="delete" />
      <h1 class="name">Item 1</h1>
    </div>
  </div>
</div>

// CSS
#list > .delete {
  color: black;
}

#list > .items > .item > .delete {
  color: blue;
}

// Javascript
$("#list > .delete").show();
$("#list > .items > .item > .delete").hide();

Pros:

  • Naming feels more natural, and names are short and clear

Cons:

  • Selecting an element for styling or manipulation is unwieldy
  • Changing the HTML structure requires changing a lot of selectors, since names are tied to hierarchical structure

Option 3...n: Some hybrid approach? A totally different approach altogether?

Keep in mind the problem of name collision when adding more elements in the future, especially when you have nested elements. Also, the ideal solution would make it easy to change the HTML structure of existing elements without too much disruption everywhere else.

20
задан Chetan 15 April 2011 в 21:58
поделиться