0
0
CSSmarkup~5 mins

Naming conventions in CSS

Choose your learning style9 modes available
Introduction

Naming conventions help keep your CSS organized and easy to understand. They make it simple to find and change styles later.

When creating styles for buttons, headings, or other page parts to keep names clear.
When working with a team so everyone uses the same style names.
When building a website that will grow bigger and needs easy maintenance.
When you want to avoid style conflicts between different parts of your site.
When you want your CSS to be easy to read and follow like a story.
Syntax
CSS
/* Example of a CSS class name */
.button-primary {
  background-color: blue;
  color: white;
}

Use lowercase letters and hyphens (-) to separate words.

Start class names with a letter, not a number or special character.

Examples
Class name for the main header using hyphens to separate words.
CSS
.header-main {
  font-size: 2rem;
}
Using BEM style with double underscore to show 'item' belongs to 'nav'.
CSS
.nav__item {
  padding: 1rem;
}
BEM modifier with double hyphen to show a variation of the button.
CSS
.btn--large {
  padding: 1.5rem 3rem;
}
ID selector naming for a unique page section like footer.
CSS
#footer {
  background-color: #333;
  color: #eee;
}
Sample Program

This example shows a card component styled with clear CSS class names using the BEM naming convention. The block is card, the element inside is card__title, and the modifier card--highlighted changes the background color.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>CSS Naming Conventions Example</title>
  <style>
    /* Block element */
    .card {
      border: 2px solid #4a90e2;
      padding: 1rem;
      border-radius: 0.5rem;
      max-width: 300px;
      margin: 1rem auto;
      font-family: Arial, sans-serif;
    }
    /* Element inside block */
    .card__title {
      font-size: 1.5rem;
      color: #4a90e2;
      margin-bottom: 0.5rem;
    }
    /* Modifier for variation */
    .card--highlighted {
      background-color: #e6f0ff;
    }
  </style>
</head>
<body>
  <section class="card card--highlighted" aria-label="Highlighted card">
    <h2 class="card__title">Welcome!</h2>
    <p>This card uses clear naming conventions for easy styling.</p>
  </section>
</body>
</html>
OutputSuccess
Important Notes

Consistent naming helps you and others understand your CSS quickly.

Use semantic names that describe the purpose, not the look (e.g., .button-primary instead of .blue-button).

Consider popular conventions like BEM (Block__Element--Modifier) for bigger projects.

Summary

Good naming conventions keep CSS organized and easy to maintain.

Use lowercase letters and hyphens to separate words in class names.

BEM is a helpful pattern to name blocks, elements, and modifiers clearly.