Naming conventions help keep your CSS organized and easy to understand. They make it simple to find and change styles later.
Naming conventions in 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.
.header-main { font-size: 2rem; }
.nav__item { padding: 1rem; }
.btn--large { padding: 1.5rem 3rem; }
#footer { background-color: #333; color: #eee; }
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.
<!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>
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.
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.