From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
A practical guide to CSS architecture. You learn how browsers score specificity (ID, class, type), why deep nesting and !important lead to style fights, and how BEM naming keeps every selector to one class. You refactor a profile card from nested CSS to BEM, handle state with a modifier class, and avoid the most common BEM mistakes.

CSS is easy to write and hard to keep tidy. You change the padding on a button in the footer, and the navigation bar at the top breaks. You add !important to fix it and promise to clean it up later. This guide is for developers who know CSS syntax and want stylesheets that stay predictable as a project grows. You'll learn how specificity decides which rule wins, then refactor a component to BEM, a naming method that keeps every selector to a single class.
This is part 3 of the Frontend & JavaScript Fundamentals series. It follows HTML architecture for product roles, so the markup here uses the same semantic elements.
Key takeaways
- Specificity is scored as ID, class and type counts. One ID beats any number of classes, so deep or ID-based selectors are hard to override.
- BEM names every part of a component with one class (
block__element--modifier), which keeps specificity flat and the HTML self-describing. - Change state by toggling a modifier class from JavaScript, not by writing inline styles.
The problem: CSS has one global namespace
Every rule in every stylesheet can match any element on the page. That is fine for a small document. In a large app it means a rule written for one component can change another one you never meant to touch.
The fix is not new syntax. It is architecture: a set of naming rules that keeps each component's styles to itself. This post moves from how selectors compete to BEM, one widely used set of rules.
Part 1: the specificity trap
Before BEM makes sense, you need to know what it protects you from: specificity.
Specificity is the weight a browser gives a selector to decide which declaration wins when several rules set the same property on the same element. Source order only breaks a tie. The heavier selector wins first. Specificity isn't the first test, though. MDN notes that it "only applies when the same element is targeted by multiple declarations in the same cascade layer or origin." Origin, !important and cascade layers are compared before specificity.
How the weight is counted
MDN describes specificity as a three-column value, written ID - CLASS - TYPE:
- ID column: each ID selector (
#header) adds 1-0-0. - CLASS column: each class (
.btn), attribute selector ([type="text"]) or pseudo-class (:hover) adds 0-1-0. - TYPE column: each type selector (
div,h1) or pseudo-element (::before) adds 0-0-1.
The columns are compared left to right. MDN puts it plainly: the selector with more IDs wins no matter what the other columns hold. Inline style attributes beat any normal rule in a stylesheet; MDN suggests thinking of them as 1-0-0-0. !important is separate from specificity, and MDN calls using it to override specificity a bad practice.
The trouble starts when you nest selectors to control layout:
/* Specificity 0-1-2: one class, two types */
.sidebar div h3 {
font-size: 20px;
}
/* Specificity 0-1-0: one class */
.card-title {
font-size: 16px;
}
Say a card with <h3 class="card-title"> sits inside a div in the sidebar. The title stays at 20px, because .sidebar div h3 is heavier. To win, you need an even heavier selector, and soon the stylesheet is full of chains like #main .sidebar .content .card-title. People call this CSS spaghetti. BEM avoids it by keeping almost every selector at 0-1-0.
Part 2: BEM (Block, Element, Modifier)
BEM is a naming method for CSS classes, developed by Yandex's frontend team, that splits a page into Blocks, Elements and Modifiers. The BEM history page says the work began in 2005 and the method took shape in 2006. The goal is that each selector is one class, and that the class name says where the element belongs.
The syntax
.block {}
.block__element {}
.block--modifier {}
.block__element--modifier {}
BEM's naming convention page lists more than one style. The classic one separates a modifier with a single underscore (block_mod). The "two dashes" style above uses a double hyphen (block--mod). Both use a double underscore for elements. Pick one style and use it everywhere.
1. Block
The BEM quick start defines a block as "a functionally independent page component that can be reused." Examples: .header, .menu, .card, .input.
2. Element
An element is "a composite part of a block that can't be used separately from it." Its name joins the block name with two underscores. Examples: .menu__item, .card__title, .input__label.
3. Modifier
A modifier defines "the appearance, state, or behavior of a block or element." In the two dashes style it follows two hyphens. Examples: .menu__item--active, .card--featured, .button--disabled.
Part 3: build a component
Time to put this into practice with a user profile card, a pattern most dashboards have.
The nested way
Here is a first attempt with plain nested selectors.
<div class="profile-card">
<img src="avatar.jpg" alt="" />
<div class="info">
<h2>Avnish Yadav</h2>
<p>AI Automation Engineer</p>
<button class="red">Follow</button>
</div>
</div>
.profile-card {
border: 1px solid #ccc;
}
.profile-card img {
border-radius: 50%;
}
.profile-card .info h2 {
margin: 0;
}
.profile-card button.red {
background: red;
}
Why this causes trouble:
- Dependencies: the image only gets its style while it sits inside
.profile-card. Move it out and the style is gone. - Leaks:
.profile-card .info h2matches everyh2in thatdiv. Add a second heading for another reason and it picks up these styles too. - Hard to override:
.profile-card button.redscores 0-2-1. Any other rule for that button has to beat it. The BEM CSS guide makes the same point: combined selectors have higher specificity, "which makes it more difficult to redefine them."
The BEM way
Now refactor the card with BEM classes.
<article class="profile-card profile-card--featured">
<img class="profile-card__avatar" src="avatar.jpg" alt="Avnish Yadav" />
<div class="profile-card__body">
<h2 class="profile-card__name">Avnish Yadav</h2>
<p class="profile-card__role">AI Automation Engineer</p>
<button type="button" class="button button--primary profile-card__action">Follow</button>
</div>
</article>
/* Block */
.profile-card {
display: flex;
border: 1px solid #e5e7eb;
padding: 1.5rem;
border-radius: 8px;
}
/* Modifier for the block */
.profile-card--featured {
border-color: #3b82f6;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
/* Elements */
.profile-card__avatar {
width: 64px;
height: 64px;
border-radius: 50%;
}
.profile-card__body {
margin-left: 1rem;
}
.profile-card__name {
font-size: 1.25rem;
font-weight: 700;
}
.profile-card__role {
color: #6b7280;
font-size: 0.875rem;
}
Look at the button. It uses a separate block (.button) because buttons appear all over the site. It also carries a card element class (.profile-card__action) to position it inside this card. BEM calls this a mix: several BEM entities on one DOM node, so you reuse styles without copying them.
Part 4: manage state with a modifier
BEM gives you a clean way to show state. Instead of setting element.style.opacity from JavaScript, you toggle a modifier class. Here is a loading state for the card.
.profile-card--loading .profile-card__avatar,
.profile-card--loading .profile-card__name {
opacity: 0.5;
pointer-events: none;
}
This is one of the few places BEM allows nesting. Its CSS guide says: "Nesting is appropriate if you need to change the styles of elements relative to the state of the block or the theme set."
In JavaScript, you only flip the class. classList.toggle() with a second argument adds the class when it is true and removes it when it is false:
const card = document.querySelector('.profile-card');
const isLoading = true; // in a real app, from your data-loading state
card.classList.toggle('profile-card--loading', isLoading);
The CSS owns how loading looks. The script only says whether it is loading. React and Vue work the same way: put the modifier in the className (or :class) when the state is true.
Part 5: common BEM mistakes
These rules come from the BEM docs, and they are worth checking in code review.
1. The grandchild element
Wrong: .card__body__title
The BEM quick start says "an element is always part of a block, not another element." It doesn't matter that the title sits inside the body in the HTML. It is still an element of the card.
Right: .card__title
2. Tying classes to HTML tags
Wrong: h2.card__title
The BEM CSS guide says BEM "doesn't use tag and ID selectors" and doesn't recommend combining tags and classes. If you later change the h2 to an h3 to fix the heading order, the style breaks. The extra tag also raises specificity.
Right: .card__title
3. Over-modifying
If you find yourself writing .card--blue--large--rounded, the method has stopped helping. Use separate modifiers (.card--large, .card--rounded) or a design token. When most of your styling is one-off tweaks like these, a utility framework such as Tailwind CSS may fit better. It is a valid alternative with a different philosophy.
| Approach | How you style | Trade-off | When to use |
|---|---|---|---|
| Nested selectors | Rules follow the HTML tree (.card .info h2) |
Specificity creeps up; styles leak to similar markup | Small pages and one-off documents |
| BEM | One class per part (.card__title--muted) |
Longer class names; naming takes discipline | Shared component libraries, plain CSS or Sass |
| Utility classes (Tailwind CSS) | Many single-purpose classes in the markup | Long class lists; repetition handled by components | Apps built from components, fast UI changes |
Tailwind's docs give the main argument for utilities: changing one element's classes "only ever affects that element." BEM gets a similar result through naming instead of tooling.
Why the extra typing pays off
Yes, BEM means more typing. profile-card__name is longer than h2.
Code is read far more often than it is written, though. When you come back months later to add a feature, .profile-card__name tells you what the element is and which component owns it. You can move the card anywhere and its styles come with it. That turns a fragile stylesheet into a set of parts you can swap.
Next in the series, JavaScript data types and functions moves from styling to the language that drives your components.
Frequently asked questions
Is BEM still useful with CSS Modules or Tailwind?
It depends on the tool. As a rule of thumb, CSS Modules already give each file its own class names, so BEM's naming adds less there, though some teams keep it for readability. With utility classes you write few custom class names at all. BEM fits best when you write plain CSS or Sass for shared components.
Should I use block_mod or block--mod for modifiers?
Both are documented on the BEM naming convention page. The classic style uses a single underscore and the "two dashes" style uses a double hyphen. The two dashes style is easier to read at a glance, but consistency across the codebase matters more than the choice.
How do I calculate CSS specificity?
Count IDs, then classes, attributes and pseudo-classes, then types and pseudo-elements, and write the counts as ID-CLASS-TYPE. Compare left to right. For example, #nav .link:hover is 1-2-0 and beats .menu .item .link a, which is 0-3-1.
Can a BEM element belong to two blocks?
Not as one class, but a DOM node can carry classes from several blocks. That is a mix, such as button profile-card__action. The .button block owns how it looks, and the card's element class owns where it sits.
When should I use !important?
Rarely. MDN calls using !important to override specificity a bad practice. With flat BEM selectors you seldom need it, because a later rule with the same 0-1-0 weight already wins.
Sources
Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead



Comments
Loading comments...