HTML Course 16.1 Naming conventions for classes and IDs


16.1 Naming conventions for classes and IDs

Proper naming conventions for class and id attributes improve readability, maintainability and consistency across your HTML projects. This section explores detailed rules, best practices and popular methodologies such as BEM, SMACSS and OOCSS, with illustrative examples.

Rules and Best Practices

  • Use only lowercase letters, digits, hyphens (-) and underscores (_).
  • Classes may start with a letter (a–z), but not with a digit.
  • Avoid spaces, special characters or uppercase letters in names.
  • IDs must be unique per page; classes can be reused.
  • Choose meaningful, descriptive names (e.g. btn-primary instead of button1).
  • Keep names concise but self-explanatory—prefer card__title over cT.
  • Avoid tying names to presentation details like colors (red-text) or sizes (big).
  • Use naming methodologies (BEM, SMACSS, OOCSS) for scalable, modular CSS.

Allowed Characters and Structure

Valid Invalid Notes
header-nav header nav No spaces allowed
user_profile user@profile No special chars except - and _
item2 2item Cannot begin with a digit
btn--disabled Btn--Disabled Prefer lowercase

Naming Methodologies

  • BEM (Block __ Element — Modifier): block__element--modifier
  • SMACSS: Categorizes rules (Base, Layout, Module, State, Theme); names reflect role (l-header, m-card).
  • OOCSS: Separate structure and skin; use abstract classes (.media, .media__img).

Good vs. Bad Examples

Bad Practice Good Practice
<div id='header1'> <header id='site-header'>
<span class='red'>Hello</span> <span class='text--error'>Hello</span>
<div class='Box1 Main'> <div class='card card--featured'>
<ul class='items'> <ul class='list list--inline'>

Example: BEM Naming in Practice

The following snippet shows a navigation block with elements and modifiers using BEM conventions:



  

Example: OOCSS Structure and Skin Separation

OOCSS encourages reusable “object” classes for layout and separate “skin” classes for visual styles:


Avatar

User Name

User bio or description goes here.

...

When to Use ID vs Class

  • ID: Unique page elements (anchors, JavaScript hooks, form wrappers). Avoid styling too many IDs—specificity wars.
  • Class: Reusable styles, layout patterns, JavaScript behavior hooks.

Summary

Consistent, meaningful naming conventions for classes and IDs are essential for scalable, maintainable front-end code. Adopt a methodology like BEM or OOCSS, stick to valid characters, avoid presentation-specific names and keep your names descriptive but concise.


Posted

in

by

Tags:

Comments

Leave a Reply