What is BEM
BEM (Block, Element, Modifier) is a component-based approach to web development. The idea behind it is to divide the user interface into independent blocks. This makes interface development easy and fast even with a complex UI, and it allows the reuse of existing code.
In this post You Don’t Need A UI Framework, I found an interesting thought about UI-frameworks usage and I see a nice way to reconcile with CSS by using BEM.
Developers often reach for UI frameworks, there are some valid use cases for them. But I’ve seen so many developers reach for these tools with unrealistic expectations about the problems they’ll solve, or how easy it’ll be to build applications with them.
How to use it
Important points
- The block shouldn't influence its environment, meaning you shouldn't set the external geometry (margin) or positioning for the block.
- You also shouldn't use CSS tag or ID selectors when using BEM.
- An element is always part of a block, not another element. This means that element names can't define a hierarchy such as blockelem1elem2.
- Create a block: If a section of code might be reused and it doesn't depend on other page components being implemented.
- Create an element: If a section of code can't be used separately without the parent entity (the block).
Block
A functionally independent page component that can be reused.
- Classname describes its purpose = menu or button
- Blocks can be nested in each other.
- You can have any number of nesting levels.
Element
A composite part of a block that can't be used separately from it.
- Classname describes its purpose = item, text
- The structure of an element's full name is block-name__element-name.
- Elements can be nested inside each other.
- You can have any number of nesting levels.
- An element is always part of a block, and you shouldn't use it separately from the block.
Modifier
An entity that defines the appearance, state, or behavior of a block or element.
- If a Boolean modifier is present, its value is assumed to be true.
- Used when the modifier value is important.
- A modifier can't be used alone. A modifier should change the appearance, behavior, or state of the entity, not replace it.
Mix
A technique for using different BEM entities on a single DOM node.
- Combine the behavior and styles of multiple entities without duplicating code.
- Create semantically new UI components based on existing ones.
File structure
BEM methodology can also be applied to CSS file structure