BEM helps keep CSS organized by naming parts clearly. SASS nesting lets you write CSS inside CSS, making it easier to follow BEM rules.
0
0
BEM naming with SASS nesting
Introduction
You want to style a button with different parts like icon and label.
You have a card component with header, body, and footer sections.
You want to keep CSS code clean and easy to read for a navigation menu.
You need to style modifiers like a button in active or disabled state.
You want to avoid repeating long class names in your CSS.
Syntax
SASS
.block {
// block styles
&__element {
// element styles
}
&--modifier {
// modifier styles
}
}The & symbol means "use the parent selector here".
BEM uses block, block__element, and block--modifier naming.
Examples
This styles a button block, its icon element, and a large modifier.
SASS
.button { background: blue; &__icon { margin-right: 0.5rem; } &--large { font-size: 1.5rem; } }
Here a card block has header and body elements, plus a highlighted modifier.
SASS
.card { border: 1px solid #ccc; &__header { font-weight: bold; } &__body { padding: 1rem; } &--highlighted { border-color: gold; } }
Sample Program
This example shows a blue button with an icon and larger size using BEM naming and SASS nesting compiled CSS.
SASS
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>BEM with SASS Nesting Example</title> <style> /* Compiled CSS from SASS below */ .button { background-color: #007bff; color: white; padding: 0.75rem 1.5rem; border: none; border-radius: 0.375rem; font-size: 1rem; display: inline-flex; align-items: center; cursor: pointer; } .button__icon { margin-right: 0.5rem; font-size: 1.25rem; } .button--large { font-size: 1.5rem; padding: 1rem 2rem; } </style> </head> <body> <button class="button button--large" aria-label="Send message"> <span class="button__icon" aria-hidden="true">📧</span> Send </button> </body> </html>
OutputSuccess
Important Notes
Use aria-label and aria-hidden for accessibility on icons and buttons.
Nesting helps avoid repeating the block name but don't nest too deep to keep CSS simple.
BEM naming makes it easy to find styles related to a component in your CSS files.
Summary
BEM naming breaks CSS into blocks, elements, and modifiers for clarity.
SASS nesting lets you write BEM styles inside the block for cleaner code.
Use BEM with nesting to keep your CSS organized and easy to maintain.