Methodology

  • Quick start
  • Key concepts
  • Naming convention
  • File structure
  • Redefinition level
  • Block modification
  • Declarations
  • Solved problems
  • Classical BEM stack
  • Data (BEMJSON)
  • Templates (BEMHTML, BEMTREE)
  • Client-side JavaScript (i-bem.js)
  • Dependencies
  • DEPS specification
  • Project stub
  • Technologies for working with files
  • Using the command line
  • Terminology
  • How to build a project
  • How to write a technology
  • Automation with express
  • ENB packages
  • File naming
  • DEPS schema
  • @bem/sdk.walk
  • @bem/sdk.config
  • @bem/sdk.naming.entity
  • @bem/sdk.naming.cell.stringify
  • @bem/sdk.naming.cell.pattern-parser
  • @bem/sdk.naming.file.stringify
  • @bem/sdk.decl
  • @bem/sdk.bemjson-to-decl
  • @bem/sdk.bemjson-to-jsx
  • @bem/sdk.import-notation
  • @bem/sdk.graph
  • @bem/sdk.deps
  • @bem/sdk.entity-name
  • @bem/sdk.file
  • @bem/sdk.cell
  • @bem/sdk.bundle
  • @bem/sdk.bemjson-node
  • Classic BEM libraries
  • bem-components
  • bem-history
  • Principles of BEM library development
  • Creating a static page
  • Starting a static BEM project
  • Starting a dynamic BEM project
  • i-bem.js tutorial
  • Dist bem-components: adding blocks to a page
  • Quick start Introduction Contents Block Element Should I create a block or an element? Modifier Mix File structure
  • Key concepts Block Element Modifier BEM entity Mix BEM tree Block implementation Implementation technology Block redefinition Redefinition level
  • Naming convention Naming rules Alternative naming schemes
  • CSS HTML for CSS Selectors Modifiers Mixes Dividing code into parts Working with redefinition levels How to switch to BEM-style CSS
  • HTML Binding blocks to a DOM node Nesting of elements Using HTML wrappers Creating HTML manually Automatic HTML generation
  • JavaScript Basic principles of the component approach in JavaScript for BEM How to switch to BEM-style JavaScript JavaScript implementation using the BEM methodology Declarative style OOP principles in JavaScript for BEM DOM representation of dynamic blocks Interaction between blocks Interaction of a block with its elements
  • File structure Guidelines for the file structure of a BEM project Approaches
  • Redefinition level What is a redefinition level? What are redefinition levels used for? How to use redefinition levels Examples using redefinition levels
  • Block modification How to choose a block modification method Using a modifier to change a block Using a mix to change a block Using redefinition levels to change a block Using context to change a block
  • Build Introduction Build stages Build result Build tools
  • Declarations Ways of obtaining a declaration Work with declarations
  • Solved problems How to simplify code and facilitate refactoring How to start reusing code without letting components influence each other How to host multiple entities on the same DOM node and avoid copy and paste
  • History Typical Yandex markup in 2005 Birth of the methodology Building up the unified framework Layout with independent blocks Lego unified framework Lego framework 1.2 (2008) Lego 2.0. Birth of BEM BEM and open source (2010) Summary
  • FAQ Why BEM? Blocks and elements Modifiers and mixes CSS JavaScript I have a question that isn't listed here How does BEM differ from OOCSS, AMCSS, SMACSS, SUITCSS? What is the difference between BEM and Web Components? What is the difference between BEM and Bootstrap? A block or an element: which one should I create? How to change the appearance of a block? Why include the block name in modifier and element names? Why create separate directories and files for every block and technology? Do block elements inherit the block's CSS properties? Why not create wrapper blocks? Why not create elements of elements (block__elem1__elem2)? A modifier or a mix: which one should I create? When to create a Boolean modifier, and when to create a key-value modifier? How to choose a name for a modifier? How to make global modifiers for blocks? Why isn't the name of the block modifier written in the element name (block_mod__elem)? How to adapt the site to different devices? Can I combine tags and classes in a selector? Can I use nested selectors? Can I use combined selectors? Can I use selectors for user-defined tags? Why shouldn't I use a CSS Reset? Why not write block_mod instead of block block_mod? When should I create helper blocks? Why is external geometry and positioning set via the parent block? Why use i-bem.js when you have jQuery?

CSS with BEM

In the BEM methodology, CSS is used for page layout and is considered one of the block implementation technologies .

The following sections cover the core principles of working with CSS:

HTML for CSS

How do i make an html wrapper, class selectors, combining a tag and a class in a selector, nested selectors, combined selectors, external geometry and positioning, styling groups of blocks.

Dividing the code into parts

Single responsibility principle

Open/closed principle, composition instead of inheritance.

Dividing code by redefinition levels and building an assembly

How to migrate from CSS to BEM

Traditionally, HTML wrappers are used for:

Positioning HTML elements relative to other elements.

Positioning elements inside a section.

The BEM methodology achieves the same results by using mixes , or by creating an additional block element. You don't need to create additional abstract wrappers. They don't add any specific features.

Positioning a block relative to other blocks

To set a block's position relative to other blocks, the best approach is usually to use a mix.

HTML implementation:

CSS implementation:

Positioning elements inside a block

The position of nested HTML elements is usually set by creating an additional block element (for example, block__inner ).

BEM doesn't use tag and ID selectors. The styles of blocks and elements are defined by class selectors.

Use selectors to specify a specific HTML element on the page, regardless of the tag. The class selector is accessed via the class attribute, which should be defined for every HTML element.

The value of the class attribute can be a space-separated list of words. This allows you to use different BEM entities on the same DOM node.

The BEM methodology doesn't recommend combining tags and classes in a selector. Combining a tag and a class (for example, button.button ) makes the CSS rules more specific, which makes it more difficult to override them. This leads to priority battles, in which stylesheets are loaded by overly complicated selectors.

CSS rules are defined in the button.button selector.

Let's say we add the active modifier to the block and set the value to true :

The .button_active selector will not redefine CSS properties of the block with the button.button selector, because button.button has higher specificity than .button_active . For successful redefinition, the selector for the block modifier also must be combined with the button.button_active tag.

As the project develops, it's possible that blocks could be added with the selectors input.button , span.button and a.button . In this case, all the modifiers of the button block and nested elements would require four different declarations for each case.

Try to use simple class selectors:

The BEM methodology allows using nested selectors, but we recommend minimizing their use. Nested selectors increase code coupling and make reuse impossible.

Valid use cases

Nesting is appropriate if you need to change the styles of elements relative to the state of the block or the theme set.

The BEM methodology does not recommend using combined selectors. Combined selectors (such as .button.button_theme_islands ) have higher CSS specificity compared to single selectors, which makes it more difficult to redefine them.

CSS rules are defined in the .button.button_theme_islands selector.

The .button_active selector will not redefine CSS properties of the block with the .button.button_theme_islands selector, because .button.button_theme_islands has higher specificity than .button_active . For successful redefinition, the selector for the block modifier also must be combined with the .button selector and declared under .button.button_theme_islands , because both selectors have the same specificity:

The name of the selector must fully and accurately describe the BEM entity it represents.

As an example, let's look at these four lines of CSS code:

We can be fairly sure that we are dealing with a single block, and its HTML implementation looks like this:

It's harder to make the same assumption with a group of selectors like this:

The names icon , text , and theme_islands aren't very informative.

The general rules for naming blocks, elements, and modifiers allow you to:

Make the names of CSS selectors as informative and clear as possible.

Solve the problem of name collisions.

Independently define styles for blocks and their optional elements.

Naming CSS classes:

BEM modifiers set the appearance, state, and behavior for blocks. A block's design is changed by setting or removing a modifier.

You can use modifiers to change a block's design by redefining specific points in the necessary CSS properties.

For example, like this:

This frees you from unneeded copying and pasting.

Mixes allow you to:

Combine the behavior and styles of multiple entities without duplicating code.

Apply identical formatting to different HTML elements.

In CSS with BEM, styles that are responsible for the external geometry and positioning are set via the parent block.

CSS implementation of a button:

In this example, the external geometry and positioning of the button block are set via the header__button element. The button block doesn't specify any margin, so it can easily be reused anywhere.

Sometimes you need to apply the same formatting to multiple different HTML elements on a page at once. Group selectors are often used for this purpose.

In this example, the text inside the article and copyright blocks has the same color and font.

Although group selectors do allow you to quickly change the design of the page, this approach tightens code coupling.

This is why BEM uses mixes to uniformly format an entire set of HTML elements.

Dividing code into parts

These basic principles for structuring and storing code are applied to BEM-style CSS:

Code is divided into separate parts. The logic of each block and its optional elements and modifiers is defined in separate files.

CSS files for each component are stored according to the rules of file system organization for a BEM project.

Dividing code into parts and controlling the project's file structure make it possible to:

Simplify navigation through the project.

Re-use and move components.

Work with redefinition levels and use an assembly .

The button block in the project's file system:

This separation allows you to quickly find needed files.

Just as in object-oriented programming, the single responsibility principle in the BEM approach to CSS means that every CSS implementation must have a single responsibility.

Responsibility: external geometry and positioning (let's set the external geometry and positioning for the button block via the header__button element).

Single responsibility selectors give the code more flexibility.

Any HTML element on a page should be open for extension by modifiers, but closed for changes. You should develop new CSS implementations without needing to change existing ones.

Let's say we need to change the size of a button. According to the open/closed principle, we extend the button.

The existing button functionality is extended using the button_size_s class (the font-size and line-height properties are redefined). Now the page has two buttons of different sizes.

Violating the open/closed principle

Changing an existing CSS implementation

The current CSS implementation of the button should be closed for changes. Changes will apply to all the button blocks.

Modification by context

The button design now depends on its location. Changes will apply to all button blocks inside the content block.

DRY ("don't repeat yourself") is a software development principle aimed at reducing repetitions in code.

In relation to the BEM methodology, the essence of this principle is that each BEM entity must have a single, unambiguous representation within the system.

As shown in the example, the btn selector repeats the existing implementation of the button block.

Let's rewrite this example using the DRY principle:

With the addition of modifiers, we got rid of the btn block.

Important The DRY principle only applies to functionally similar components of a page, such as buttons.

As you can see, there are some small external differences between the buttons. The DRY principle is about exactly these types of entities – they are functionally similar, but they have different formatting.

There isn't any reason to combine different types of blocks just because they have, for instance, the same color or size.

Inheritance is a mechanism for defining a new CSS class based on an existing one (a parent or base class). The derived class can add its own properties, as well as use the parent properties.

New CSS implementations are formed in BEM by combining existing ones. This keeps the code uncoupled and flexible.

Let's say we have three existing implementations:

A button (the button block).

A menu (the menu block).

A popup window (the popup block).

Implement a drop-down list (the select block).

Developing a drop-down list with a custom appearance is not an easy task. However, if you have ready-made components (a button, a popup window, and a menu), you just need to correctly describe how they interact.

Working with redefinition levels

Applying BEM principles to CSS allows you to separate block representations into different levels.

Separating into levels allows you to:

Implement a new appearance for a block on a different redefinition level while preserving the previous one by inheriting and extending it.

Completely override a block's appearance (redefine it).

Add blocks with a new representation.

You can use redefinition levels to create a universal CSS block library and change it on the project level. You can then use use an assembly to only include the desired block representations in the project.

During the build, the desktop.css file gets all the basic CSS rules for the button from the common level and the redefinition rules from the desktop level.

The mobile.css file will include the basic CSS button rules from the common level and the redefinition rules from the mobile level.

Separating representations of the button block by levels allows you to:

Completely override a block's appearance on another redefinition level.

common.blocks/button/button.css

desktop.blocks/button/button.css

Add to or partially change a block's appearance on another redefinition level.

mobile.blocks/button/button.css

How to switch to BEM-style CSS

To implement BEM principles in a project:

Put aside the DOM model and learn to create blocks.

Don't use ID selectors or tag selectors.

Minimize the number of nested selectors.

Use the CSS class naming convention in order to avoid name collisions and make selector names as informative and clear as possible.

Work in the terms of blocks, elements, and modifiers.

Move CSS properties of a block to modifiers if they seem likely to be changed.

Divide code into small independent parts for ease of working with individual blocks.

Re-use blocks.

How to start using BEM concepts in an existing project

Create new components using the BEM methodology, and change the old ones as needed.

When desigining blocks, follow the principles covered above.

Use prefixes in names of CSS classes (such as bem- ) in order to differentiate the new code from the old code.

Once you are familiar with BEM-style CSS, you can look at the specifics of implementing BEM for JavaScript .

  • Read next HTML

Avatar of Robin Rendle

The following is a collaborative post by guest Joe Richardson , Robin Rendle, and a bunch of the CSS-Tricks staff. Joe wanted to do a post about BEM, which we loved, and just about everybody around here had thoughts and opinions about BEM, so we figured we’d all get together on it and do it together.

The Block, Element, Modifier methodology (commonly referred to as BEM ) is a popular naming convention for classes in HTML and CSS. Developed by the team at Yandex, its goal is to help developers better understand the relationship between the HTML and CSS in a given project.

Here’s an example of what a CSS developer writing in the BEM style might write:

In this CSS methodology a block is a top-level abstraction of a new component, for example a button: .btn { } . This block should be thought of as a parent. Child items, or elements , can be placed inside and these are denoted by two underscores following the name of the block like .btn__price { } . Finally, modifiers can manipulate the block so that we can theme or style that particular component without inflicting changes on a completely unrelated module. This is done by appending two hyphens to the name of the block just like btn--orange .

The markup might then look like this:

If another developer wrote this markup, and we weren’t familiar with the CSS, we should still have a good idea of which classes are responsible for what and how they depend on one another. Developers can then build their own components and modify the existing block to their heart’s content. Without writing much CSS, developers are potentially capable of creating many different combinations of buttons simply by changing a class in the markup:

See the Pen BEM example by CSS-Tricks ( @css-tricks ) on CodePen .

At first this syntax might seem slower than simply making a new class for each type of button, but this is not the case for several reasons we’ll cover.

Why should we consider BEM?

  • If we want to make a new style of a component, we can easily see which modifiers and children already exist. We might even realize we don’t need to write any CSS in the first place because there is a pre-existing modifier that does what we need.
  • If we are reading the markup instead of CSS, we should be able to quickly get an idea of which element depends on another (in the previous example we can see that .btn__price depends on .btn , even if we don’t know what that does just yet.)
  • Designers and developers can consistently name components for easier communication between team members. In other words, BEM gives everyone on a project a declarative syntax that they can share so that they’re on the same page.

Harry Roberts identified another key benefit of using a syntax like BEM when he writes about improving developer confidence:

This is the main reason we end up with bloated code bases, full of legacy and unknown CSS that we daren’t touch. We lack the confidence to be able to work with and modify existing styles because we fear the consequences of CSS’ globally operating and leaky nature. Almost all problems with CSS at scale boil down to confidence (or lack thereof): People don’t know what things do any more. People daren’t make changes because they don’t know how far reaching the effects will be.

Likewise, Philip Walton argues that this problem can be fixed if enough developers stick to the principles of BEM:

While 100% predictable code may never be possible, it’s important to understand the trade-offs you make with the conventions you choose. If you follow strict BEM conventions, you will be able to update and add to your CSS in the future with the full confidence that your changes will not have side effects.

So if developers can work on a project more confidently, then they’re sure to make smarter decisions about how these visual components should be used. This methodology might not be a perfect cure for all these ailments, but it certainly gives developers a standard on which to write better, more maintainable code in the future.

Another smart part of BEM is that everything is a class and nothing is nested . That makes CSS specificity very flat and low, which is a good idea . It means you won’t end up fighting with yourself over specificity.

Let’s take a look at some of the problems with BEM…

Problems with BEM CSS

Of course nobody will twist your arm if you break from BEM rules. You could still write a CSS selector like this:

That looks like it has parts of BEM going on, but it’s not BEM. It has nested selectors, and the modifier doesn’t even accurately describe what’s going on. If we did this, we’d be screwing up the specificity flatness that is so helpful with BEM.

A block (such as .nav ) should never override the styles of another block or modifier (such as .btn--orange ). Otherwise this would make it almost impossible to read the HTML and understand what this component does; in the process we’re bound to greatly shake another developer’s confidence in the codebase. This goes for HTML, as well: what would you expect if you saw the following markup?

What’s probably going on here is that an element in a completely unrelated block has the code a developer needed, but the child elements don’t require a .nav class as the parent. This makes for an exceptionally confusing and inconsistent codebase which should be avoided at all costs. So we can summarize these problems by:

  • Never overriding modifiers in an unrelated block.
  • Avoiding making unnecessary parent elements when the child can exist quite happily by itself.

More examples of BEM in action

Accordion demo.

See the Pen BEM Accordion by CSS-Tricks ( @css-tricks ) on CodePen .

In this example there is one block, two elements and one modifier. Here we’ve can created an .accordion__copy–open modifier which lets us know we shouldn’t use it on another block or element.

Navigation demo

See the Pen BEM Menu by CSS-Tricks ( @css-tricks ) on CodePen .

This navigation demo has 1 block, 6 elements and 1 modifier. It’s even perfectly OK to create blocks without modifiers at all. At some point in the future a developer can always bolt on (or bind to) new modifiers so long as the block remains consistent.

Dislikes of BEM

Perhaps you don’t like the double-underscores or double-dashes thing. Fine, use something else that is unique that you will consistently enforce.

Here’s another sentiment:

Not sure I'm sold on BEM. .site-search .site-search__field .site-search–full Why not: .site-search .site-search input .site-search .full — Samuel Fine (@samuelfine) March 11, 2015

Those last three selectors all have different specificity levels. They either require parents or not. Without any rules in place, they don’t say as much as the ones on top.

Is it possible that this tiny, isolated example feels perfectly fine to you and never ends up biting you in the butt? Perhaps. But the more CSS you have in a project, the more little things like this add up, the more specificity and complexity battles you go through.

BEM sounds super useful if you don't know how HTML or CSS work. — Samuel Fine (@samuelfine) March 11, 2015

Not to pick on Samuel here, but his sentiments are shared by a lot of people so it makes for a good example. They see BEM, and they just outright reject it. If you want to dislike BEM, that’s absolutely fine, but I think it would be hard to argue that having a set of rules that aid in understanding and assist in keeping CSS maintainable is a bad idea.

In the SMACSS methodology, you’re likely to find a CSS classname with three letters. Modifiers then follow the module name with a hyphen:

That’s just a different naming approach to the same kind of problem. It’s pretty similar, but you’re just being more specific about dependencies and keeping specificity flatter.

In OOCSS , blocks are similarly generic.

So you would use multiple classes in the HTML for variations. The inside part isn’t named like it has a dependency, so it is less clear but potentially more reusable. BEM would do .mod__inner and .mod--talk and .mod--talk__inner .

These are just variations on methodology. Remember that nobody is twisting your arm here, these are self-imposed rules where the value comes from following them.

Sass and BEM

For those of you writing Sass and enjoy nesting as a way of scoping styles, you can still author in a nested format, but get CSS that isn’t nested, with @at-root :

And you can get as abstract as you want! Check out Danield Guillan’s BEM Constructor or Anders Schmidt Hansen’s Expressive BEM .

To wrap things up I think it’s fair to say that even though BEM won’t solve all our problems it is extraordinarily useful for constructing scalable and maintainable interfaces where everyone on the team should have a clear idea of how things can be improved. This is because a great deal of front end development is not just about the nice tricks that solve one little problem in the short term; we need agreements, promises and binding social contracts between developers so that our codebase can adapt over time.

Generally I like to think of BEM as an answer to Nicolas Gallagher’s question:

Replace "can you build this?" with "can you maintain this without losing your minds?" — Nicolas Gallagher (@necolas) July 24, 2013

Further reading

  • The BEM project website
  • Side effects in CSS
  • Chaining BEM modifiers
  • BEM principles
  • More transparent UI code with namespaces

I’m with Samuel on this one, I don’t like it.

I understand the pros and cons, but for me the cons outweigh the pros.

Sometimes we’ll add a prefix to a class name so the relationship between things is obvious, i.e:

.form .form-fieldset .form-text

.form .form fieldset .form input[type=text]

But that’s as far as we take it. This idea behind dashes and underscores is kind of messy and confusing to me.

Yeah, the dashes and underscores look wierd

For me, it seems to make it much easier to look at one element and tell where all (or at least a good solid chunk) of its styling is coming from.

In the .form-fieldset example above, what if I want a specialized fieldset in a form that’s green? Now I have .form-fieldset-green –is this a green fieldset inside a form or is a green class on an element inside the fieldset inside the form ?

To me that distinction between elements through the __ and modifiers through -- works wonders. Now I know that .form__fieldset--green is green fieldset inside a form at quick glance.

Agreed, let’s not go back to 2006 and have ourselves some huge bowls of class soup

A while ago I stumbled upon this: https://github.com/rstacruz/rscss . Started using it and in my opinion its clearer then lots of underscores etc. And code looks cleaner too.

Re-factoring is easier when using BEM. Without dashes and underscores, I bet you will HAVE to use nesting and with nesting you will run into cascading overwrites and uncertainty when you need to rename or remove classes. You also will not be able to reuse nested class that easily in a new place and you will have to re-factor again. Here you can find more details on the topic with example.

I am a big fan of BEM.I am using BEM for all my office and personal projects from last two years.BEM never been a pain in the ass, especially when you work on large projects and large teams. the html looks clean, readable and easily understandable. helps in creating a perfect modularization for style sheets. Helps and tends you to write or develop more modular codes. with the help of sass or less you can make website authoring to a kickass experience.

Most of my friends complained about the underscore and long names which look’s weird, need to type more, lot of bullshit blah blah. but the main benefit I see from my experience

Understanble HTML document Helps you in writing modular stylesheet Easy stylesheet maintenance BEM make you think webpage as composition of components which helps in creating reusable stylesheets BEM improves readability in javascript code while dealing with class names.

My biggest benefit that I got from BEM is, it trained me a lot to thinking in modular way. not only css,but also in programming. I can feel the change and the advantages that i gained.I don’t how to explain it, yeah.. its true.

Give it a try.

SCSS and BEM works for me, I would normally write something like:

What if you have…

…and need to CTRL+F for .block__title? Wouldn’t it make more sense for all classes to be easily searchable? Nesting looks cleaner, but I think there’s a definite drawback in not being able to CTRL+F for something inside the codebase.

BEM (and other component methodologies) promote a one-component-per-file approach. So finding stuff begins with opening the file for that component (Ctrl-P or Ctrl-T or whatever Navigate-to-File shortcut your editor has). This is great because it immediately reduces the scope of your search. If the file is too big to visually scan, you simply Ctrl-F for &__title.

@Jeremy – @Mike summed it up pretty well. Being that the block has been named correctly and your file structure is logical you won’t struggle to find what you need. I had the same worry before but haven’t looked back since. Choose a file structure that suits you and the project best, and use CTRL + SHIFT + F in Sublime to find a class quickly across multiple .scss files. Maps can help too.

Thanks guys. That makes sense.

The lates Sass version supports BEM in the following way:

Which would result in

You can see it online here – http://sassmeister.com/gist/fe753a8228da9ed45136

The same syntax would work for LESS as well. In case any LESS users were curious.

There is no need in @at-root #{&}__element , because &__element is also working in sass.

I didn’t like the verbose look of BEM at first but it’s amazing how quickly I got over it. It’s easier for me to understand structure now glancing at BEM CSS and it helps coming up with naming too.

Personnaly I love this : https://github.com/rstacruz/rscss it put a little bit deepness into selector but it correct something that bother me with bem : the length of the class title.

I don’t know in what mesure confortable selector is important with deepness, but I do prefer it.

I’ve been using BEM on my last few projects and I think it works well. The only thing I’ve done differently is switch up the underscores and dashes since I prefer dashes and my CSS usually contains more elements than modifiers.

I love BEM. At first I shyed away from it because it’s so ugly but then I realised I can use mixins to abstract the formatting in css. In scss it’s more characters than it’s worth but with indented sass it’s kind of beautiful

gracefully compiles into

Here are the mixins for those wandering

I like this method. Thanks, Charlotte.

Hi guys, what do you think about following library which takes similar approach? https://github.com/danielguillan/bem-constructor

This looks great! Thanks Charlotte :)

That looks great, thanks!

even i also don’t like this… may be we can go for camel case pattern. .btn {} /* Element that depends upon the block */ .btnPrice {}

It will be help full to maintain the code pattern in js also….

Sass + BEM is a great reason to use BEM. Both seem to be meant for writing CSS that you DON’T GET CONFUSED BY.

I guess my BEM is more just .parent-child and I use few modifiers, if ever. I have taken to writing high level layout blocks with a l_ prefix like:

BEM would be more like .l_header__nav , but I use dashes simply because if I want to select any element of the selector, dashes are better for double-clicking in text editors. (Underscores are word-characters so double-clicking will select the whole selector.) May be a weird reason to do that, but it helps my workflow.

I’ll chime in as, for my sins, I find CSS architecture eternally fascinating. IMHO any approach that attempts to rationlise and enforce HTML classes and CSS selectors is better than no system. The more complicated the system/UI, the truer this becomes. You can dislike BEM syntax (I’m not a fan) but the principles buy you far more than using no system at all (particularly at scale). I also dislike the practice in Sass of using the parent selector to nest; you lose the one to one relationship with your markup (you can’t select a HTML class from Dev tools and search for the selector in a Sass codebase). For very large complex UIs (and depending upon how you are building them) I have found different approaches more advantageous (I call my own Enduring CSS ) than BEM, principally the use of a micro-namespace as a means of containment. I have found this in practice to be more robust, faster to iterate on, more understandable from a naming POV (that last point is entirely subjective though). Whatever, you choose, however you adapt from what you begin with, to have some approach is infinitely better place to be than no defined approach at all!

Hey Ben, if you structure your Sass files so that each block gets its own folder and its own scss file, then searching by a selector becomes no longer necessary as looking at .footer__copyright will lead you to the footer folder at once without any searches, then it’s only a matter of finding __copyright in that particular file :)

“you can’t select a HTML class from Dev tools and search for the selector in a Sass codebase).”

Use sourcemaps instead….

@Alex I’m using Sublime at present, I can double-click an HTML class in the DOM, CMD+C and then in Sublime CMD+R and CMD+V to find that Symbol project wide. Within a second it takes me straight to that selector in my Sass/CSS ready to type. I find that infinitely quicker than manually browsing for a component folder (I have in excess of 100 components).

@ewfwefewfewewf – souremaps mean I need to edit in the browser. I prefer to edit in my text editor.

OFFTOPIC–

souremaps mean I need to edit in the browser. I prefer to edit in my text editor.

Although you can edit in the browser (Chrome) and save the file , that’s a browser feature rather than a source maps feature.

How I edit in my text editor and use source maps:

Enable source maps (Chrome) . View the line a specific rule is located in the source/preprocessed file. Edit.

If you use Sublime Text you don’t have to “find” that rule, just press CTRL+G (Windows) and type the line number.

To clarify your point about SMACSS, if .callout is a variant of .module , it should be named .module-callout .

There is very little difference between BEM and SMACSS. In SMACSS, it talks of modules, sub-modules, and sub-components. These map directly to blocks, modifiers, and elements.

Is there a single developer here who has actually used BEM on a project and not bought into it? its easy to dismiss it because it ‘looks funny’ or you ‘dont like the __ or –‘ but thats just left over thinking from the ‘best practices’ which we already know are not necessarily best at all. The bigger the project and the more people contributing to it – the bigger the benefits of something like BEM.

As for Sam’s tweet, would you honestly feel comfortable joining a project and changing the .full rule? I highly doubt it, which will lead to higher specificity selectors and as the project grows – less consistency/maintainability. (which wastes time & money and doesn’t look good)

Give it a try, you might be surprised.

Exactly, once you forgo any initial concerns and actually start using this approach on a project it’s amazing how useful it becomes, and how strange not using it seems.

I challenge any naysayers to give it a go on a project, I think you’ll be surprised at how it changes the way you see your CSS. It’s almost indispensable once you get your head around it.

This. After couple of projects with BEM (and SASS) I realized that there had been significantly less issues with classnames and conflicts. It’s just one of those things that kind of silently grew on me.

One think I like about it is that I can safely use generic words (block, area, container) as BEM -element names. It really speeds up the development when I don’t have to think new names that much.

And, like many have said here, the @at-root can be removed with new SASS version. Like this:

Great write up on BEM. I see that there are mixed opinions on it whicvh is great and reflects the expressiveness of css.

I find BEM to be both scalable and readable (which is why we use it). At first we used it purely to identify parent-child relationships and I struggled to find a use for modifiers at all but the more we used it the more we realised that used correctly you can build extremely flexible and lean architecture!

If anyone is interested I wrote a little WordPress script to create dynamic BEM menus and (if you like BEM) I’m sure you will appreciate how much easier it is to create complicated multi level navigation with BEM syntax rather than .menu-name li > ul > li{} .

If you have never used BEM before it serves as a practical usage example:

https://github.com/roikles/Wordpress-Bem-Menu

Too verbose, and looking too weird. Intermixing underscores with double dashes with single dashes with camelCaps. No thank you sir. Just using single dashes for inheritance AND sublevel elements works absolutely fine, doesn’t look weird or verbose, and doesn’t invite to write selectors that are too specific.

Thanks for a great article Joe, Robin and the bunch.

In my experience it depends a lot on the complexity of a given project, personal preference (my mental model) and the team I’m in.

Some projects are too small (not very complex) to make sense using a BEM-ish approach, while other projects that require high modularization have, in my experience, benefited greatly from BEM.

In the case of the startup team I’m a part of, it just makes it easier to discuss and understand our code when things are very component-based and follows BEM. Well, the “Roberts meets Gallagher meets Snook meets our own blend” version of BEM, that is.

For us, we need things to be very much like LEGOs – able to move around independently, be removed or added easily – since we need to iterate quickly based on customer feedback and user testing results. BEM helps us a lot with that.

Truth be told, when I first saw BEM I was not very convinced, but after trying it out I began to really enjoy it. Maybe it’s like React’s “give it five minutes” .

All of the benefits of BEM make sense to me and I like it. My biggest complaint with it is the classnames get really really long. Especially the deeper you get in the module.

For instance assume the following HTML/CSS:

.accordion .accordion__title .accordion__title__icon

And then let’s say I want a modifier on .accordion__title__icon –

class=”accordion__title__icon accordion__title__icon–facebook”

I realize that we could shorten the name of the class, but that sort of defeats the purpose of making everything easy for other developers to quickly understand what’s going on.

With BEM you should probably avoid using code like “accordion__title__icon accordion__title__icon–facebook”.

You’d be better off making ‘accordion’ and ‘icon’ as separate components. Then just combining them.

This has the advantage of each is useable elsewhere in your site without needing the other. The goal is to abstract each piece so it can be used independently elsewhere.

Hey Neal, I agree with @Andrew H here in that you usually don’t need to nest so deep. If you have an element inside of an element then the top-most element can probably be a separate block. I once wrote an article about BEM mixins , if you are interested, please take a look.

I agree with guys above. However I don’t like that pattern of specifying base class together with modifier class, it is really redundant ( class=”accordion__title__icon accordion__title__icon–facebook” ). Here you can learn about a simple workaround.

I’m fine with enforcing consistency and having a naming convention but the dual underscores looks horrible, especially when combined with single/double hyphens.

It’s an oft-repeated misconception that BEM specifically requires double underscores or dashes. That’s their default recommendation, in order to support hyphen-separated names, e.g. .menu-button__submit-icon . But it’s valid to adopt a Pascal-cased approach e.g. .menuButton_submitIcon . See the examples in their docs .

I suggest you read ‘Modern CSS Architecture and Front-End Development’ by Harry Roberts from the Smashing Book #4.

If you like the concepts of BEM but not the syntax, there are other options, like SUIT: https://github.com/suitcss/suit/blob/master/doc/naming-conventions.md

I take things one further. I use namespaces in my CSS.

Harry shows some of the benefits of it here: (has Harry ever done a guest blog here? He should. Try to get him to. ) http://csswizardry.com/2015/03/more-transparent-ui-code-with-namespaces/

I only make one amendment. I use ‘.namespace-block-element–modifier’ because underscores are to easy to miss.

Seems like the first “C” in CSS is the most dreaded thing… :-)

Rightfully so, since you can’t stop the cascade.

For those of you who don’t like to write long CSS class names. Stop doing it by hand, try BH template engine for this: http://bem.github.io/bh/

This template code:

applied to this json:

will give you this html:

for the love of god i hope this doesn’t catch on. its ugly as sin and feels like a time machine to 2004

specificity is NOT your enemy if used correctly

All the comments about how “ugly” the double underscores is seems to be missing the point. Whether or not it’s ugly, BEM is certainly clear what the intentions are. Clarity and structure is the point not how pretty or ugly the markup and CSS is.

@Brendan, I did use it on the project and came to dislike it even more. It is abuse of CSS. One even may venture further and claim that it basically goes against some core principles of CSS. It may have it’s place, but it is overused already.

First, kudos for trying it before judging it. However, I do strongly disagree that it BEM is abusive, or antithetical, to CSS. Can you expound on this strong viewpoint?

CSS is a vague specification. It’s unique design goals included compactness, device-agnosticism, and shared authority between publisher and user (which turned out to have little long-term importance). Nothing in BEM contradicts these tenets in any way. BEM merely adds “cooperative componentization” to CSS: rules are grouped together logically, and each group respects a common set of strict constraints on selector construction.

Aside from the ugly__syntax--conventions (which can be changed) my biggest objection is that you have a chain of class names in your HTML, e. g. class="btn btn--big btn--orange"

This way you have a lot of variations which can be combined freely … but does this help to get a consistent style on your website? If you wouldn’t do classes that are named based on characteristics like size or color, but based on function, maybe suddenly there are considerably fewer meaningful combinations.

And many of them could be done by giving a parent element a reasonable class. Why make the button bigger? Because the user has a touch device? Then give the body the class .touchDevice and many more elements can be adapted simultaneously. Yes that creates specificity, but as el generico wrote: It’s not your enemy if used correctly.

If possible and not too confusing I try to group my classes in CSS so that I don’t have to define basic things repeatedly. Example:

This way I don’t have to write class="btn btn-deactivated" but class="btn-deactivated" is enough. What’s in the classname that’s in the style, btn and deactivated.

I like my CSS and HTML short and concise. Class chains clearly aren’t my thing.

Yey, finally I found another person with same view on the problem! I’m so happy now :) Please take a look at my article which describes another way to group modifier classes, using attribute selectors. I wonder what you think.

Sergey, the idea to use the CSS selectors [class^="block--"], [class*=" block--"] is great. So you can also shorten your class lists in the CSS files.

I’ve used something similar on a website that consisted of equivalent slides. With [class^="slide-"] I gave the base styles to all slides; while with .slide-1 , .slide-2 , .slide-3 etc. I set individual properties like the background image.

Sure, you could write short and concise CSS in BEM methodology.

One approach is to use preprocessors like SASS, so you can define your styleguide explicitly:

You also can use full BEM stack and therefore avoid writing HTML by hand:

Couldn’t we use partial attribute selectors in our CSS too ?

[class*=–disabled]{pointer-events:none;}

Wouldn’t this cover any .block–disabled item.

Fine question. The semantics of “disabled” might mean different things in different logical contexts. If we’re talking about an input field, disabled might mean “this control is read-only”. At the higher levels of abstraction that BEM blocks enable, we might have a listing of Product blocks in our Product Listings block. Such a Product might itself have a “disabled” state, which could mean “this product is unavailable for sale because it’s out of stock”. These two definitions of disabled are different, and will have different presentational implications.

With your suggestion, we ignore and do not permit logical context in our code design. The word “disabled” is assumed to have one common meaning regardless of the context in which it’s applied. Ultimately, that discourages working at higher levels of abstraction because it’s cumbersome and painful to re-define the meaning of class names with the cascade. And without abstraction, we are forced to think about the entire front-end in terms of low-level HTML primitives, which wastes our limited cognitive capacity. In the worst case it exhausts that capacity, making the front-end indecipherable, unpredictable, and prone to regression.

Was hoping the article would address my main gripes with BEM (which I otherwise love), which sometimes make me end up writing crazy long classess like section-name__content__blurbs__blurb__title :

How do you decide what is a block? Surely the entire page isn’t a single block, but how do you decide how to decompose it? How do you name elements whose only purpose is to make some CSS hack/feature work? Imagine you have a hero element, which to the eye just contains a headline and a tagline as ostensible children. You’d love your classes to be .hero , .hero__headline , and .hero__tagline , but you needed a couple intermediate elements to accomplish some design goal (e.g. a wrapper, a pre-flexbox container for vertical centering — use your imagination). Those elements need styles, so are you forced to write .hero__wrapper__container__headline ? Sometimes I do it, but I also think of it as a reductio ad absurdam for the whole convention. Other times I fudge and say “the wrapper element isn’t so much a child of the parent as part of the implementation of the block, so I’ll call it .hero--wrapper and reduce the length of the child selectors by one.” But this dilutes the naming convention.

Namespaces. Need a hack to make code work? Prefix with “_”. http://csswizardry.com/2015/03/more-transparent-ui-code-with-namespaces/

“How do you decide what is a block?” Any element that is self-containing and can be decomposed. If you can move this anywhere on the page and have it function exactly how it does anywhere else. That is a block. Navigation, content area, side-bar, footer, header, carousel, etc.

Zack, there’s no reason to mirror nesting structure in element’s name. Hero layout could be something like this:

Unless you have elements with the same name on different nesting levels (which is not a great idea on its own) you still got a bulletproof protection against css selectors’ collision.

Roman, I’ve never seen a problem to layout in more classic and semantic way:

Therefore, LESS or SCSS code looks something like that:

Clean and simple, isn’t?

This layout could be easily broken by nested block, as block1’s selectors would affect block2 elements.

BEM naming may be not that clean and simple, but it guarantees bulletproof incapsulation.

I’ve forked the first pen to provide a brief example of BEM templating: http://codepen.io/sameoldmadness/pen/yyWXZm?editors=001

It’s upsetting to see a lot of discussion in the comments around “proper” class names.

After all, BEM is not telling you how to name your classes. Instead it is proposing a way to separate your code into atomic reusable components.

Just look at the basic block declaration in BH syntax:

It has nothing to do with html, css or js.

But the block itself could contain logic implemented in all of these technologies (and even more).

For the .mod--talk__inner example, I prefer keeping the modifiers on the block whenever possible. So, this would be:

Otherwise, you’d need a new modifier class for each element of a block.

I suppose this messes with specificity, but .mod–talk .mod__inner should have precedence anyway.

But, I guess this brings up the question: Should elements be nested inside blocks?

You’re spot on with the first block of code – only nesting them inside a modifier, or as a separate modified class e.g. .mod__inner--wide {}

The following would be redundant, as .mod__inner is named in such a way that we already know it’s an element of .mod :

You’re reducing the amount of fighting you’ll have to do with specificity as components develop.

First of all, I hope you are modularizing your CSS whether you use BEM or not. Secondly, take a look at your current projects. Do you often nest unrelated modules inside of your modules? If that’s the case then use the BEM approach. If not, use an approach that makes the HTML and CSS more readable.

I wrote Title CSS as a way to easily locate module classes and create a scope for short descendant classes. https://github.com/cuth/Title-CSS

I find that using “orange” as a class name in the example is really a bad idea.

Because, of course you’ll have someone write a .sidebar .orange { color: blue; } , BEM or not.

Why not use .primary or .secondary ?

Here is a good blogger explaining semantic css.

I often get the feedback from the backend guys that using BEM creates much more work for them and the project manager doesn’t like to hear that. Their argument is that it is easier for them to output

form class=”signup__sidebar”>

As the first variant is already coming out of the CMS just like that, but the second requires more coding work to get like that. And it is not just about the form, but any other plugins/extensions they use for the CMS.

How should this be seen?

In my example above variant one was:

and the second was:

I just call it .butts, as in buttons.

so it would be like,

.butts>span:first-of-type {}

.butts>span:last-of-type {}

I dunno why you would ever give children of these bad boys classes.

In my opinion, BEM is an absolute craziness and it makes HTML and CSS code bizarre.

Okay, even if your project is very complicated with a lot of stuff delivered by many teams, so why don’t follow Web Components approach that keeps everything clear and simple? http://webcomponents.org/

Because of it is not supported by browsers. And polyfills are very slow.

So, if I were to follow this structure, would this be appropriate for a navigation element?

And how much is too much? Say for example I have some small styled element in the link, like an icon, would that add a fourth layer? How far is too far when dealing with BEM? Can you go too far?

Correct code would be:

@Sergey – You’ve got your elements and modifiers mixed up:

Thanks David! I’m only good at canonical BEM naming:

This thread perfectly reveals how developers couldn’t catch BEM conventions right.

I use my own system as I’m not a fan of the BEM class names. I get the whole single selector thing but I find it much quicker creating templates with shorter class names.

Sub element class names always start with double underscore and modifiers with a single dash. I find it’s much easier to read in both the HTML and SCSS, for example:

I do something similar but with the child combinator in internal selectors. Otherwise, you expose yourself to risk of regressions and selector battles when composing components. E.g. if this Accordion ends up composing an ArticleBlurb, which may have its own __content, then the Accordion’s __content styles will be applied to the ArticleBlurb’s. This is easily addressed with the child combinator:

You lose flexibility of adding arbitrary elements into the Accordion structure, but that’s a feature not a bug. A consistent structure makes components much easier to manage.

Knappster, I also do the same nesting style (along with Mike) but my naming convention is different.

Since “Accordion” and every other module class starts with an uppercase class name, I’m free to name a descendant class with any lowercase name since classes are case sensitive.

For more information on this naming convention: http://www.sitepoint.com/title-css-simple-approach-css-class-naming/

Keep in mind that we should also be focusing on the efficiency of our CSS. I would argue that efficiency should trump our ease of development when it comes down to it.

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS

Nick, I strongly disagree. “Premature optimization is the root of all evil.” There is generally far greater risk to a project from unorganized CSS than from unoptimized selectors. Is performance/efficiency something to be aware of and understand? Yes. But it should not be the primary focus. Optimize only when necessary. Unlike most programming languages, CSS is a particularly sensitive software technology in this regard, as it doesn’t provide strong abstraction mechanisms behind which one can hide gnarly optimizations.

That said, there are other ways to optimize presentation than through selectors. Limit use of shadows and transparency. Prefer CSS3 transitions/animations to JavaScript ones. Concatenate stylesheets to reduce HTTP overhead.

Valid point, my example is a bit over simplified I think.

As a new web designer & developer it is useful for breakpoints for responsive design. Because codes are more cleaner.

Introduction to BEM Methodology

When building smaller websites, the way developers structure their CSS code is usually not a big issue. However, when it comes to larger, more complex projects, code organization becomes crucial.

In this article, Toptal Freelance Software Engineer Tomislav Matijević introduces us to BEM methodology and explains how this CSS practice can massively improve code maintainability, speed up the development process, and streamline the teamwork of developers by arranging CSS classes into independent modules.

Introduction to BEM Methodology

By Tomislav Matijević

Tomislav is a software engineer well versed in front-end technologies, particularly in vanilla JavaScript and React.js.

PREVIOUSLY AT

What Is BEM Methodology?

When you are building smaller websites, how you organize your styles is usually not a big problem. You create your usual files, write all the needed CSS, and that’s all. However, when it comes to larger, more complex projects, how you organize your code becomes crucial . How the code is structured is even more important if you are working in a team consisting of multiple front-end and back-end developers.

BEM Methodology will massively improve code maintainability and speed up the development process

Today, there are plenty of methodologies with the aim of reducing CSS code and making your CSS code more maintainable. In this article, I am going to explain and provide a few examples of one of them: BEM . BEM stands for B lock E lement M odifier. The main idea behind it is to speed up the development process, and ease the teamwork of developers by arranging CSS classes into independent modules. If you ever saw a class name like header__form--search , that is BEM in action. Yes, classes can be named very long, but they are all readable and understandable.

Note that the best practice is to use BEM only with classes, and not IDs because classes allow you to repeat names if necessary and create more consistent coding structure. Also, if you want to break your website into organized modules, it should consist of the same structure: block, element, and modifier. Where each block can have multiple elements, and both block and elements can have multiple modifiers. However, let’s first start with the basic BEM structure and explain it with examples.

A block represents an object in your website. Think of it as bigger structural chunks of your code. Most common blocks on every website today are header, content, sidebar, footer, and search. Blocks in BEM are always a starting point of chaining your CSS classes on to. Take a look at a few block examples:

  • a search form

An element is a component within the block that performs a particular function. It should only make sense in the context of its block:

  • a content article
  • a menu item
  • a search input field

A modifier is how we represent the variations of a block. If you’ve ever used Bootstrap, then the best example would be the button sizes. Button sizes are just size variations of the button itself, which makes it the modifier:

  • a content featured article
  • a menu link
  • a search field with or without icon

Naming Conventions

The primary purpose of BEM methodology is to make names of CSS selectors as informative and transparent as possible. Original BEM style is defined in this way:

Block name is usually a single word like .header , but if you have longer block definition then it is divided with a single hyphen - :

Element name starts with double underscore __ :

Modifier name starts with single underscore _ :

There is only one very critical rule in BEM methodology - a modifier cannot be used outside of the context of its owner.

You can use btn_big only if header is defined also.

Bad example:

Good example:

Beside these original BEM styles, there are alternative naming schemes like Harry Roberts and CamelCase styles.

Harry Roberts style example:

CamelCase style example:

There are few others too, but these two are the most common ones. Personally, I am a fan of the naming convention proposed by Harris Roberts, which has the following rules:

  • Names are written in lowercase
  • Words within the names of BEM entities are separated by a hyphen -
  • An element name is separated from a block name by a double underscore __
  • Boolean modifiers are delimited by double hyphens --
  • Key-value type modifiers are not used

The reason why this naming convention is much better formed than others is that you can easily distinguish modifier element from others. In original naming conventions, modifier would be defined like this:

But as you can see, there is not very much difference between a single and double underscore. On the other hand, double hyphen provides clean separation, and you can see the modifier instantly:

BEM Example in Different Formats

Please note that besides CSS, BEM is also very useful in organizing your JSON, XML, tree files, or any format supports nesting. Think of BEM methodology as a good way to build your UI.

HTML structured in BEM format

Let’s consider the following HTML, structured in BEM format:

The same can be achieved using JSON and XML format.

File System Organization of a BEM Project

In BEM, it is critical to organize your files in a correct manner. Not only is BEM providing you a great organization of CSS classes and making them completely understandable, but also gives you a very maintainable file structure. Let’s take an example project, using BEM file organization technique with SASS files:

As you can see above, just by seeing the subfolder structure inside your main folder, everything is clear and organized. In this way, it makes no difference who is working after you or if you are working after someone, because it is incredibly easy to follow the same pattern.

Dividing BEM Project into Platforms

Besides just organizing your files using BEM methodology techniques, you can also go into more specific things. For example, if you are building a web project which is going to be fully responsive, and the client specified that some blocks on the mobile are totally different than on desktop devices, it would be best to divide your BEM folder structure into platforms. Example of organizing buttons on various platforms:

Note that this is just an example if you want to organize your whole project using BEM methodology. File tree with BEM structure is not mandatory to use BEM correctly, you can use BEM just in some segments of the project. So far I haven’t been using this strict BEM file structure organization where every element and modifier has its file created. Instead, I am just creating a file structure for blocks which are having a declaration of its elements and modifiers.

Tree Organization of a BEM Project

BEM in Practice

Since you are now familiar with naming conventions, I will demonstrate BEM methodology in practice. Let’s say that we have this HTML code in action:

With the following CSS markup applied:

Now, don’t be mislead. In our examples so far we almost always had a block, element, and modifier, which doesn’t always have to be the case.

For example, let’s say we have a block named person . A person has legs and hands, it can also be female or male. If we want to define a male person with a right hand it will look like this:

Now you can see the real meaning of the BEM. We defined a person which modifier is a gender. Since it doesn’t matter if a person is male or female, it has a hand, and hand is an element. And again, each person can have right or left hand which is again a modifier.

In another case, if we want to define general person with a single hand, we will do it like this:

As you can notice, once you get comfortable with BEM it’s very easy to structure your CSS and HTML structure with it.

Using BEM with CSS Preprocessors

Personally, I can not imagine starting any new project without using one of the CSS preprocessors. As you all know, preprocessors are a great thing and they are providing us a lot of benefits, and most importantly they are a perfect match with BEM methodology.

In the following example, you can see the most typical example of BEM, in combination with SASS:

SASS code will compile into the following CSS:

If you want to go even further, you can use a handy SASS mixins for BEM:

And you can use it like this:

Which will produce the following CSS output:

I know that most likely you won’t have a use case this long, but this is a great example of how BEM is used and why it’s so powerful, both in small and large scale projects.

Starting Your BEM Project

As explained in the official BEM documentation , the easiest way to start you own new BEM project is to use existing GIT repository . Simply use Git clone command:

Next, go to a newly created directory and install all dependencies:

All required dependencies will be installed:

BEM dependencies

Build the project using ENB :

Run a server mode for development:

As a result, the following message appears:

Now, this means that the server is up and running. You can now check the results on this address:

As you can see, there are a lot of elements already created which are defined inside bemjson file which is located here:

You can see and explore the current structure of the file that is generating all that HTML, which you see at your localhost index.html file. We are going to alter this file to get our “Person” BEM project which we explained in a previous chapter. You can remove (or comment) the whole code from index.bemjson.js file, and replace it with this one:

Now, the following HTML will be generated:

As you can see from the code above, the default BEM coding scheme was used in this scenario since we are just using default settings which BEM provided to us. There are a lot more commands and options which you can explore and use, such as creating new pages, blocks, or modifying BEM HTML. I will not go too deep into this, and it can all be found in the official BEM documentation .

BEM Advantages and Concerns

Advantages and Concerns

  • BEM is excellent for maintaining. How many times have you had to work after someone on a large scaled project and you are just too afraid to change anything without something unknown collapsing? When using BEM, you know the exact purpose of the element and in which block it may appear.
  • Class names are logical and intuitive, and every member of the team knows what that element does on the website. BEM gives everyone on a project a declarative syntax they can share so they’re on the same page.
  • BEM eliminates nested CSS selectors. Every single HTML element has its own CSS class, and by its name you know what its purpose is. One selector to rule them all .

Concerns and Common Mistakes

  • Do not go too deep into nesting. The main rule should be not to use more than two levels of parent and child.
  • Be careful with where you start your block scope. A common mistake here is when a developer is using block, but he is not realising that at the later point of development that same block will have main parent block which will possibly break the rule with nesting.
  • Avoid SASS @extend. To quote Harry Roberts on this:
You can create a greater number of combinations in the view by not ‘tying’ classes together in Sass. The HTML has a much better paper trail in that you can see every class acting on a piece of the DOM. Your CSS stays much slimmer in that you don’t have to create new placeholder classes (or the manifest classes that combine them) every time you want to create a new piece of UI.

When I saw BEM coding scheme for the first time, my first thought was:

These classes are just too long to write and read.

But after giving it a try, now I can not imagine starting a new project without using it. For me, BEM massively improved my code maintainability, and I can for sure say that every developer who is going to be “thrown” into the BEM-based project will catch up really quickly with the whole code structure.

Despite all this, there’s a lot of discussion on social networks about BEM. Some say BEM isn’t good, wondering why they should write such long name classes instead of just use default HTML nested elements. Well, no one says that you must like BEM, but the fact is that the majority of front-end developers embrace it and find it extraordinary useful.

  • Methodology

Tomislav Matijević

Osijek, Croatia

Member since February 11, 2015

About the author

World-class articles, delivered weekly.

By entering your email, you are agreeing to our privacy policy .

Toptal Developers

  • Algorithm Developers
  • Angular Developers
  • AWS Developers
  • Azure Developers
  • Big Data Architects
  • Blockchain Developers
  • Business Intelligence Developers
  • C Developers
  • Computer Vision Developers
  • Django Developers
  • Docker Developers
  • Elixir Developers
  • Go Engineers
  • GraphQL Developers
  • Jenkins Developers
  • Kotlin Developers
  • Kubernetes Developers
  • Machine Learning Engineers
  • Magento Developers
  • .NET Developers
  • R Developers
  • React Native Developers
  • Ruby on Rails Developers
  • Salesforce Developers
  • SQL Developers
  • Tableau Developers
  • Unreal Engine Developers
  • Xamarin Developers
  • View More Freelance Developers

Join the Toptal ® community.

BEM Methodology In CSS: A Quick Start Guide

January 14, 2020

This is a quick start guide to learning BEM , the component-driven CSS methodology.

If you want to start practicing and applying BEM to your projects, this guide will help you get started.

Bonus: Download a free cheat sheet that will show you how to quickly get started with BEM.

Ready? Let’s dive in:

  • BEM overview
  • E - Elements
  • M - Modifiers

BEM Overview

BEM (Block-Element-Modifier) is a CSS naming convention developed by the team at Yandex to improve scalability and maintainability in web development.

Put simply, the idea of BEM is to “divide the user interface into independent blocks” by naming CSS classes in the following methodology:

  • Block: an independent component that can be reused (e.g. with class name .nav )
  • Element: a child within a block that cannot be used separately from that block (e.g. with class name .nav__item )
  • Modifier: a variation in the style of either a block or modifier (e.g. with class name .nav--dark )

Let’s dive into some real CSS examples to get a hang of this thing.

Blocks are reusable components. Like buttons, cards or form fields.

When naming your blocks, focus on describing its purpose (i.e. what it is) rather than its state (i.e. what it looks like).

For example, .btn or .nav follows the correct naming convention for a block.

.big or .bright-pink describes how it looks, so doesn’t scale well when you want to change the design later on.

If you’re wondering how to place blocks within blocks (for example, a button inside a nav), here’s a short article to help you with that.

Inside blocks are where elements live. Elements are dependent on their parent block, and so cannot be used without them.

Elements also have a unique CSS class naming convention which works like this:

.block__element

For example, using the .card component, an element inside the card component (like an image) would have a class name like .card__img .

The element name always appends the block name, separated by a double underscore __ .

It’s important to note that the second code snippet avoids using more than 1 selector to target the styles (e.g. like .card img {} ).

It’s considered best practice to use a BEM element class and use that directly instead (like .card__img {} ).

Following this approach reduces the chance of cascade issues down the line.

If you’re wondering on how to handle BEM elements that are nested 3 or 4 layers deep, check out this article on the topic.

When you have varying styles in blocks (or elements), that’s where modifiers come in.

For example, your ‘card’ block might have a light and dark version. Or you might have primary and secondary buttons.

Modifiers have a unique CSS naming convention which works like this:

block--modifier or block__element--modifier .

That’s right- BEM modifiers can be applied to both blocks and elements.

Let’s dive into some bad and good practices:

It’s considered bad practice to use a modifier class in isolation (i.e. without the block or element class).

That’s because the modifier is meant to add incremental style changes to the block.

Therefore, whenever using a modifier, ensure it’s used with the base class:

And that’s it!

Those are the fundamentals to get you off and running with BEM.

If you’re interested to learn more about the ‘why’ behind BEM, I recommend checking out this CSS Tricks article .

Like learning anything new, practicing is key. Give BEM a shot in your next project and see where it takes you!

Want to become an advanced CSS & Sass developer?

Levelling up your CSS & Sass skills in 2021 is a great idea. Here's why:

  • Increase your employability and value as a front-end developer
  • Learn how to style your websites and applications in clean, efficient code
  • Use tooling and techniques like BEM, flexbox, grid & more to improve your code

Tom Ray

By Tom Ray , a front-end developer who lives in London with his fiancée and cat Arnold .

BEM Methodology

Article info.

  • CSS Architecture
  • Cascading Style Sheets
  • Less (Stylesheet Language)
  • Sass (Stylesheet Language)
  • Naming Conventions
  • Coding Guidelines

Article Versions

  • 6 2022-01-14 06:12:24 3099,2298 6,3099 By arvindpdmn Adding CSS tag
  • 5 2020-12-11 13:16:38 2298,2264 5,2298 By arvindpdmn Modular CSS Frameworks changed to CSS Architecture in See Also.
  • 4 2020-10-14 10:06:55 2264,1198 4,2264 By arvindpdmn Clarifying double-hyphen style
  • 3 2019-02-08 12:41:43 1198,1197 3,1198 By arvindpdmn Publishing.
  • 2 2019-02-08 12:36:51 1197,1193 2,1197 1 By mohanjo Adding content. Ready for review/publish.
  • Submitting ... You are editing an existing chat message. All Versions 2022-01-14 06:12:24 by arvindpdmn 2020-12-11 13:16:38 by arvindpdmn 2020-10-14 10:06:55 by arvindpdmn 2019-02-08 12:41:43 by arvindpdmn 2019-02-08 12:36:51 by mohanjo 2019-02-06 06:16:05 by mohanjo All Sections Summary Discussion Sample Code References Milestones Tags See Also Further Reading
  • 2022-01-14 06:12:40 - By devbot5S [URL Check] The following URLs in this article are outdated. Please update. Missing URLs: References: 404 HTTP response: http://en.tadatuta.ru/methodology/ References: 404 HTTP response: https://putaindecode.io/en/articles/css/modules/ Further Reading: 404 HTTP response: https://m.alphasights.com/bem-i-finally-understand-b0c74815d5b0
  • 2020-12-11 13:16:56 - By devbot5S [URL Check] The following URLs in this article are outdated. Please update. Missing URLs: References: 404 HTTP response: http://en.tadatuta.ru/methodology/ References: 404 HTTP response: https://putaindecode.io/en/articles/css/modules/ Further Reading: 404 HTTP response: https://m.alphasights.com/bem-i-finally-understand-b0c74815d5b0
  • 2020-10-14 10:07:17 - By devbot5S [URL Check] The following URLs in this article are outdated. Please update. Missing URLs: References: 404 HTTP response: http://en.tadatuta.ru/methodology/ References: 404 HTTP response: https://putaindecode.io/en/articles/css/modules/ Further Reading: 404 HTTP response: https://m.alphasights.com/bem-i-finally-understand-b0c74815d5b0

BEM logo. Source: P. Silva 2016.

When updating web/mobile user interfaces, frontend developers often worry about breaking existing code or introducing inconsistencies. Selecting elements on a UI is often problematic because of long cascading rules, nested styles, rules that are unnecessarily high in specificity, and naming everything in the global namespace. BEM provides a modular approach to solve these problems.

BEM is a methodology, an approach and a naming convention to write better CSS styling and achieve consistent JS behaviour. BEM stands for Block , Element and Modifier . These three are called BEM Entities .

BEM is not a W3C standard but it's recommended by those who have adopted it and reaped its benefits. Among its adopters are Yandex, Google, BBC, Alfa Bank, and BuzzFeed. BEM also works nicely with CSS languages (Sass, etc.), and frontend frameworks (React, etc.).

An overview of BEM. Source: Adapted from BEM 2019b.

BEM is a component-based approach to design a user interface for the web/mobile. For example, we can identify components such as header, menu, logo, search and login on a typical web page. In BEM , we call these components blocks , each having a well-defined purpose or semantics. It's also apparent that a block can contain other blocks within it. However, each block is also independent of other blocks and can be reused elsewhere. For example, it's not necessary that the login block must be part of the header block. It could be moved to a sidebar in a redesigned page layout.

Blocks can also contain elements that cannot exist outside their parent blocks. For example, a menu block is composed of menu items, each of which is an element in BEM terminology.

Finally, an element within a block can be selectively modified depending on the context. For example, in a menu block, the active menu item could be styled differently. This modification is done using modifiers . Modifiers are optional.

BEM enables flexible maintainable code. Components can be reused. Code becomes more consistent since the rules are clear. It's easier to scale to large projects. Teamwork is easier because everyone is familiar with BEM conventions. Since the approach is based on independent blocks, work can be clearly partitioned, with each team member working on a different block.

More specifically, every BEM CSS class is unique and self-sufficient. BEM doesn't need nesting of styles. We don't need long and inefficient selectors to match specific elements. BEM avoids name collisions due to its consistent naming convention. The naming convention also makes the CSS self-documenting: the relationships among DOM nodes is easier to see. DOM nodes are selected more efficiently with managed specificity.

Let's consider the following: block-name__elem-name_mod-name_mod-val . We note that names are all in lowercase, underscores are used as separators between BEM entities, and hyphens are used within names for better readability. We use double underscore to separate block from element; single underscore to separate block/element name from its modifier; single underscore to separate modifier name and modifier value.

  • main-menu_hidden : main-menu is the block, hidden is the modifier.
  • menu_theme_islands : menu is the block, theme is the modifier, islands is the theme being specified (modifier value).
  • menu__item_type_radio : menu is the block, item is its element, type is item's modifier, radio is the modifier's value.
  • main-menu__item_black-listed : main-menu is the block, item is its element, black-listed is item's modifier.

  • Two Dashes : block-name__elem-name--mod-name--mod-val : double hyphens are used between elements, modifiers and values.
  • CamelCase : blockName-elemName_modName_modVal
  • React : BlockName-ElemName_modName_modVal
  • No Namespace : _modname : no reference to block or element and hence of limited usefulness.
  • Styling : CSS , Stylus, Sass
  • Behaviour : JavaScript, CoffeeScript
  • Templates : BEMHTML, BH, Pug, Handlebars, XSL
  • Documentation : Markdown, Wiki, XML

An important principle of BEM is to avoid selectors based on ID or tag name. Only class names are used, and these can be reused easily regardless of the tag. It's also allowed to use multiple BEM entities on the same DOM node.

We can use nesting in BEM but it's not recommended. Nesting increasing code coupling and inhibits reuse. Likewise, combined selectors (eg. .btn.btn_error ) are not recommended.

Use only a single double underscore in a name: c-card__img rather than c-card__body__img . Use namespaces to improve readability: c- for component, l- for layout, h- for helpers, is- or has- for states , js- for JavaScript hooks.

External geometry and positioning (such as padding) should be done on parent node so that the current block can be reused elsewhere. Use mixes to apply the same style to multiple DOM nodes. This approach is better than using group selectors.

Take an object-oriented approach to design. Design in terms of reusable blocks. Use principles such as single responsibility principle and open/closed principle. Don't repeat yourself ( DRY ). Prefer composition over inheritance. Organize your files into a clear folder structure.

Since BEM avoids the use of ID s or tag names, class names have to be unique. Giving these names can be a difficult task. Long class names bloat markup. To reuse UI components, we need to explicitly extend them.

As an example, a modifier will need its own class name but giving names for each DOM node that needs to be styled with this modifier can be cumbersome. An alternative is to use utility classes, named with u- prefix. The trade-off is that this will result in nested CSS . Thus, a DOM node is selected as menu__item u-active rather than menu__item-active .

Since DOM nodes are marked with BEM entities, BEM creates a semantic overlay on the DOM . This is called BEM Tree . While some regard this as a useful thing, others claim that BEM unnecessarily makes the markup semantic.

The first version of Cascading Style Sheets ( CSS ) comes out as a W3C Recommendation. The idea of having style sheets can be traced to Tim Berners-Lee, who used it in his NeXT browser (1990), and Pei Wei's Viola browser (1992). Håkon Wium Lie released an initial draft in October 1994.

At Yandex, developers find that for large projects, layouts are becoming difficult to maintain. Long cascading rules and dependencies cause changes in one web page to affect many others. To solve this, they introduce the concept of blocks . A block is part of a page or layout defined semantically or visually. A block is given a unique CSS class name. Nodes within blocks are called elements . For example, logo is an element with a header block.

Block names use prefixes to emulate namespaces. Each prefix has its own semantics: b- for blocks, h- for block wrappers, l- for layouts, g- for global styles. This is also when modifiers are introduced to indicate block state or property. Modification can be context-dependent such as location; or context-independent.

With the release of Lego 2.0, the unified styling framework at Yandex, BEM is formally born. Blocks are primary units. A block can be used anywhere on the page. Each block is stored in a separate folder with its own documentation. Blocks used are noted in XML files and used to generate CSS files.

Folks at Yandex invent Absolutely Independent Blocks ( AIB ) to solve the problem of slow DOM updates. Each DOM node has its own class. Tag rules are avoided in CSS .

BEM is open sourced along with some essential BEM tools.

CSS Modules is born with the initial commit happening in May 2015. BEM requires developers to choose unique class names and does not provide encapsulation. CSS Modules solves this by dynamically creating class names and localising styles. Thus, tooling is just as important as conventions. CSS Modules doesn't replace BEM . It makes it easier to implement BEM .

Sample Code

  • /* Source: https://css-tricks.com/forums/topic/less-bem/ Accessed: 2019-02-08 */   /* Less */ block { &__element { & --modifier-one { color : red ; } & --modifier--two { color : blue ; } } }   /* CSS compiled from the above Less code */ block__element --modifier-one { color : red ; } block__element --modifier-two { color : blue ; }  
  • <!-- Source: https://www.smashingmagazine.com/2016/06/battling-bem-extended-edition- common-problems-and-how-to-avoid-them/ Accessed: 2019-02-08 --> < div class = "c-card" > < div class = "c-card__header" > < h2 class = "c-card__title" > Title text here < / h2 > < / div >   < div class = "c-card__body" > < img class = "c-card__img" src = "some-img.png" alt = "description" > < p class = "c-card__text" > Lorem ipsum dolor sit amet, consectetur < / p > < p class = "c-card__text" > Adipiscing elit. < a href = "/somelink.html" class = "c-card__link" > Pellentesque amet < / a > < / p > < / div > < / div >  
  • BEM. 2019a. "The history of BEM." BEM. Accessed 2019-02-06.
  • BEM. 2019b. "Key concepts." BEM. Accessed 2019-02-06.
  • BEM. 2019c. "Naming convention." BEM. Accessed 2019-02-06.
  • BEM. 2019d. "CSS with BEM." BEM. Accessed 2019-02-06.
  • Berner, David. 2016. "Battling BEM CSS: 10 Common Problems And How To Avoid Them." Smashing Magazine, June 01. Accessed 2019-02-06.
  • Bos, Bert. 2016. "A brief history of CSS until 2016." W3C, December 17. Accessed 2019-02-06.
  • Dutartre, Thibaut. 2016. "Toward CSS modules." Putain de code!, February 23. Accessed 2019-02-06.
  • Levine, Garrett. 2016. "React Components & B.E.M." Medium, October 02. Accessed 2019-02-06.
  • Matijević, Tomislav. 2016. "Introduction To BEM Methodology." Engineering Blog, Toptal, April. Accessed 2019-02-06.
  • P. Silva, Pablo Henrique. 2016. "BEM — Blocks, Elements and Modifiers." tldr tech, on Medium, April 12. Accessed 2019-02-06.
  • Perezpriego. 2017. "CSS Evolution: From CSS, SASS, BEM, CSS Modules to Styled Components." Medium, January 03. Accessed 2019-02-06.
  • Powell, Kevin. 2018. "Why I use the BEM naming convention for my CSS." YouTube, November 09. Accessed 2019-02-06.
  • Rendle, Robin. 2015. "BEM 101." CSS-Tricks, April 02. Updated 2016-03-09. Accessed 2019-02-06.
  • Roberts, Harry. 2016. "Nesting Your BEM?" CSS Wizardry, November 28. Accessed 2019-02-06.
  • Shirshin, Maxim. 2014. "Scaling Down The BEM Methodology For Small Projects." Smashing Magazine, July 17. Accessed 2019-02-06.
  • Tadatuta. 2019. "BEM Methodology." Tadatuta. Accessed 2019-02-06.
  • css-modules GitHub. 2017. "css-modules/css-modules." October 28. Accessed 2019-02-06.

Further Reading

  • Popa, Andrei. 2016. "BEM I (finally) understand." AlphaSights, on Medium, May 31. Accessed 2019-02-06.
  • Belaya, Inna. 2018. "BEM For Beginners: Why You Need BEM." Smashing Magazine, June 18. Accessed 2019-02-06.
  • Hubert, Victor. 2017. "A practical introduction to the BEM CSS methodology." Medium, January 19. Accessed 2019-02-06.

Article Stats

Author-wise stats for article edits.

Avatar of user mohanjo

  • Browse Articles
  • Community Outreach
  • About Devopedia
  • Author Guidelines
  • FAQ & Help
  • Forgot your password?
  • Create an account

bem methodology css

CSS BEM Methodology

Feb 24th, 2024

In small-scale websites, organizing CSS is not that hard. With a limited number of files, CSS can be easily managed.

However, In large-scale websites, CSS management can become challenging, particularly when selectors are defined randomly. This where CSS methodologies come into play. Because applying a methodology for CSS ensures consistency in the creation of styles, preventing the challenges of managing CSS.

This guide will discuss the one of the mostly used CSS methodologies, BEM. Before delving into BEM, let's take a closer look at what CSS methodologies are and why we should consider using them.

What are CSS Methodologies?

Simply put, CSS methodologies are approaches or strategies for organizing and structuring the code that defines the styles of a web page.

These methodologies provide us guidelines and best practices so that we can write maintainable, scalable, and efficient CSS code.

Most popular ones include:

  • SMACSS (Scalable and Modular Architecture for CSS): SMACSS is an approach that divides styles into five categories: Base, Layout, Module, State, and Theme.
  • OOCSS (Object-Oriented CSS): OOCSS promotes the idea of creating reusable and modular CSS components. It encourages separating structure (layout) from skin (appearance) and reusing styles across different components.
  • Atomic CSS: This methodology involves creating small, single-purpose utility classes that can be combined to build complex layouts. Each class represents a specific style or property, making it easy to compose styles.
  • ITCSS (Inverted Triangle CSS): ITCSS is a scalable and maintainable CSS architecture introduced by Harry Roberts. The architecture is represented as an inverted triangle, and it consists of several layers, each serving a specific purpose.

What is BEM

BEM, which stands for Block, Element, Modifier, is a naming convention for CSS classes that aims to create more maintainable, scalable, and reusable CSS code.

BEM divides web components into three different parts, including:

Blocks: Represent independent, reusable components of a web page, like a header, a button, or a form.

Elements: Refer to parts of a block, like a title within a header, a price within a product block, or a label within a form field.

Modifiers: Represent different states or variations of a block or element, like a button being disabled or a form field being in error.

CSS BEM Naming Convention

The BEM CSS naming convention is structured using underscores and hyphens:

  • block__element--modifer

Now, let's see an example where we have a card component that will be utilized throughout our application.

In this example, card is the block, title , description and button are the elements, and primary and secondary are modifiers.

If you want to style this component with SASS, here is how it looks like:

Points To Consider

When using the BEM methodology, there are several important points to consider.

Modifiers Also Can Be Applied To Blocks

Modifiers can be applied to both blocks and elements. This allows you to change the appearance or behavior of an entire block, rather than just a single element. For example:

Blocks can be nested in each other.

Blocks can be nested inside each other to create complex components. This allows you to create reusable blocks that can be combined in different ways. For example:

Elements can be nested inside each other.

Elements can also be nested inside each other to create more complex components. This can be useful when you need to create more complex UI elements. For example:

It is not possible to use an element independently of its corresponding block

Elements should always be used within their corresponding block. This helps to prevent naming conflicts and ensures that your code is easy to understand. For example:

An element can not be part of the another element

An element should not be a part of another element. This can make your code more difficult to read and maintain. For example:

A modifier can not be used alone

Modifiers should always be used in combination with a block or element. This ensures that your code is consistent and easy to read. For example:

Best Practises

And here is some best practises to consider while using the BEM methodology for naming CSS.

  • Avoid nesting too deeply: While nesting is allowed in BEM, it's important to avoid nesting too deeply. This can make your HTML and CSS difficult to read and maintain. Aim for no more than three levels of nesting.
  • Use clear and concise class names: The BEM methodology encourages the use of descriptive class names. Avoid using abbreviations or acronyms that are not immediately understandable.
  • Keep modifiers simple and reusable: Modifiers should be used sparingly and kept simple. Avoid creating modifiers that only apply to a single instance of a block or element. Instead, create modifiers that can be reused across multiple instances.

In this article, we have covered CSS BEM methodology used for naming CSS classes, along with examples. At the end of the article, let's remind you that BEM methodology is an option for naming CSS, using it may have pros/cons depending on your projects and team.

Thank you for reading.

Writing cleaner CSS code with BEM

Bobate Olusegun

May 25, 2023 · 7 min read

Writing cleaner CSS code with BEM

Clean and organized code is crucial in modern web development projects, and developers are constantly seeking ways to improve code maintainability and organization. Thankfully, various techniques exist to achieve this goal, including the popular Block Element Modifier (BEM) methodology — and this article will explain how BEM works and why you should start applying it.

In this article, we’ll delve into the world of BEM, exploring its many advantages, usage, and implementation strategies for both HTML and CSS. By using BEM, developers can implement a structured, modular approach to naming conventions in HTML and CSS, resulting in code that is easier to read, more maintainable, and less prone to errors. This article will equip you with an understanding of the importance of BEM in modern web development and the ability to write cleaner, more maintainable code for your next project or product. Let’s get started!

What is BEM?

BEM is a naming convention for HTML and CSS classes that helps developers create maintainable and organized code. It provides a structured format for naming the HTML and CSS classes, leading to the breakdown of our webpage into smaller components (block, elements, and modifiers components). It was created in the mid-2000s by developers working on the complex user interface of the Yandex search engine. The developers were struggling with maintaining their rapidly growing CSS codebase. They needed a structured approach to naming conventions in HTML and CSS to make their codebase more maintainable, scalable, and reusable. After experimenting with several methods, they settled on BEM, which aims to create a hierarchy of components on the webpage. In 2010, they published their approach in a blog post, which gained popularity in the web development community. Today, BEM is widely adopted as a naming convention for HTML and CSS by companies such as Google, Airbnb, and GitHub, and has spawned many tools and resources to assist developers in implementing the methodology more efficiently.

There are many benefits to using the BEM methodology. Here are a few reasons for you to consider using BEM:

  • Reusability : BEM methodology allows us to generate code that enables the reuse of components in multiple instances, resulting in a well-structured and organized hierarchy of components on the webpage. As a result, it becomes possible to use blocks in various locations on the page.
  • Maintainability :BEM’s well-defined structure facilitates targeted changes or updates to particular sections of a webpage. By employing BEM, we can ensure smooth code maintenance, faster updates, and minimize coding errors, resulting in an error-free codebase.
  • Better accessibility : The naming convention offered by BEM enhances accessibility as it helps technologies, such as screen readers, to detect, interpret, and understand the content on a webpage with greater ease.
  • Better collaboration : BEM’s naming convention simplifies teamwork among developers. By adopting a unified naming convention for classes, developers can comprehend and edit each other’s code more effortlessly, ultimately fostering better collaboration and teamwork.

Before you continue reading, take this practical explanation as the primary goal of BEM. For instance, if your friend or another developer were to look at your CSS code, they should easily understand the code. It means that your code should be readable, clear, and concise. In other words, your code should have a consistent style that your friend or another developer can easily understand.

When should we use BEM?

We mostly used BEM when dealing with projects having a huge codebase comprising multiple pages. Here are some practical samples of where we can implement BEM:

  • Large-Scale Projects : We can introduce BEM when we have a project with a large codebase, which comprises multiple developers building different parts of the project. Using BEM, we can easily maintain the project and reduce the risk of error and code conflict.
  • Accessibility-focused projects : The BEM methodology will make our website more accessible to users when projects prioritize Search Engine Optimization (SEO). With BEM, our website would be more accessible to users when they use technology that detects the contents of a webpage.

The breakdown of the keyword “BEM”

BEM illustration

BEM is a keyword that represents three entities:

This is a fundamental entity in the structure of BEM, which is very useful in organizing and structuring CSS and HTML code for websites and web applications. A block is an independent User Interface (UI) entity that represents a reusable component of a web page. Some examples of the block entity on the webpage are the navigation bar , sidebar , header , etc.

Example of the block naming method:

In the code snippet above, we can easily deduce that the developer is trying to style a button (a block in this case). It means that when choosing a name for a block element to style, we should choose names that are easy to read and understand. Also, the block name should start with a small letter like the block name btn above.

When applying the block method while setting the class name, we should remember the name should be descriptive and show the function or purpose of the block. That is the sole aim of the block naming convention. You are not required to consider other features (like appearance - color) of the block element when creating a class name. The modifier entity deals with appearance, so never try to do this:

Instead, try to follow best practices by just using a word or set of descriptive words in alignment with the function of the element.

Another school of thought when working with the block is when we want to use more than a word for our block name. The creators of BEM had this in mind while developing it, and thus, they came up with a solution - separating words with hyphens.

For example, a product list block would be named “product-list”:

When using the block entity, you should always try to integrate the following guidelines:

  • Choose semantic block names: Choose names that explicitly define the function of the element, not its appearance.
  • Use class names consistently: BEM enforces having class names for every element in your code. Therefore, all element entities within a block should have a class name, including the block entity. With this‌, nothing is affected by changing the class style. Instead of using element selectors, assign a class name for each element in your codebase.
  • Separate block styles from their elements: BEM encourages us to separate block styling from other components, like the element. We often use Block styles in other parts of the code, which is why code conflicts may occur when combining the style of a block with another component.

Following the guidelines above will ensure that integrating the block entity when defining classes for our markdown or when styling (CSS) is a seamless process.

The letter’ E’ in the BEM symbolizes the Element entity. Element, unlike the block entity, is dependent. They are the children of the block entity, as they can not stand alone. We can find them inside a block - they live inside the block.

Note : an element can only have a parent (just a block it’s tied to), and we can’t use it outside that block. Let’s take an example of a block - header. Inside the header block, we have things like logos, links, and buttons embedded in it. These things found in the header block are the “elements.” Now, how do we create an element name? An element name starts with the parent name (block name), followed by double underscores, and ends with the element name.

The CSS code:

Our HTML code:

In the code sample above, we have a parent element (div) with a block name of header . Inside it, we have an image element with an element name header__logo .

Nesting Elements within the same block

Nesting elements is embedding an element inside another element within the same block. Using the example of a header block with a navigation element inside it ‌containing a menu-item element (ul tag - an unordered list), we can then say the menu item is nested in the navigation element.

Nesting Elements are very useful in representing complex or hierarchical relationships between parts of a Block. However, it is ‌advisable to keep the Element hierarchy flat and avoid nesting elements deeply. Deeply nested elements can make the HTML and CSS code more complex and harder to read and maintain. It can also lead to specificity issues when styling the nested elements, making it harder to override styles or change the layout later.

Therefore, use nesting sparingly only when it is necessary to represent the structure of the block. It is often better to use multiple blocks or elements at the same hierarchy level to represent different parts of the page rather than nesting elements intensely.

Here is a code sample to explain the theory of nesting of elements:

We can deduce from the code that we still implement the standard naming convention for defining element names, even when elements are being nested. We could have written the code above this way:

When defining an element name for a nested element, you shouldn’t prefix it with the parent element name (header__link in this case), which results in this - header__link__menu-list . Just prefix it with the block name (header), followed by double underscores, then the element name, which results in this - header__menu-list (for this example).

Here are some key things to consider when using the Element entity:

  • We use elements to represent sub-components of a block.
  • Assign a descriptive name to your element and always follow the standard naming convention, even when working with nested elements.
  • Avoid using an element outside the block it belongs to.
  • Reduce the level of nesting elements.

Considering these tips will let you adapt to industry-standard usage of the Element entity in the BEM methodology.

This determines/defines the appearance, state, or behavior of a Block or an Element independently (without creating a new Block or Element from scratch).

We separate the modifier name from the block or element name by using two hyphens (--) . The ideal way of naming modifiers is to prefix them with a double hyphen (--) , though some people use double underscores (__) or a single hyphen (-) . I would advise you to take it as an ideal practice to use the double hyphen (–-) as a prefix for the modifier name and not the other methods in other not to mix the modifier with another entity, like an element since it uses the double underscore (__) prefix.

Here is the syntax:

We add Modifiers to Blocks or Elements by adding their name as a suffix to the Block or Element’s class, separated by two underscores.

Note, Modifiers are optional, but you can choose to use them because of their efficiency in creating visual styles and adding variation to Elements and Blocks. Some examples of modifier names are disabled , primary , and so on.

For example, within a div container are two buttons with identical styles except for their state (active or disabled). To accomplish this, we utilize a Block named card that contains an Element called buttons. From there, we apply Modifier to the buttons we want to assign a state. The HTML code

In the code above, we have two modifiers named card__buttons–active and card__buttons–disabled , respectively.

When creating a name for any entity in the BEM methodology, try to use names that people who are not developers can easily understand.

Even if a non-developer looks at this code, they can easily predict that we are styling buttons on the card and that we assigned one to be active (a state that shows it has already been clicked) and the other to be disabled (a state that makes the button unclickable).

Modifiers are optional, but if you choose to use them, you need to note these things:

  • Use them judiciously and only when essential to prevent needless complications in our code.
  • When creating a modifier name, try to be clear and specific about its purpose, like disabling buttons, changing the font size, etc.
  • Avoid using a Modifier to override a style. Instead, consider adjusting the style to your desired outcome.

Session Replay for Developers

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay suite for developers. It can be self-hosted in minutes, giving you complete control over your customer data

Happy debugging! Try using OpenReplay today.

The Practical Aspect

In this section, we’re going to take a look at a real-world example that demonstrates the BEM methodology.

BEM card

The case study for this segment is a Card structure built with HTML and CSS - the image above.

From the image, we can deduce the following entities:

  • Block : The card itself is the Block; it can also be referred to as the Parent of all other elements since other elements are embedded in it.
  • Element : Here, we can say that we have just two direct elements, a header component, and a button component. But in the actual sense, we have five elements - a header element with three elements (image element, title element, and description element) nested within it and a button element that has two actual button elements nested within it.
  • Modifier : Just as I said earlier, modifiers are used in place of setting appearance, and tweaking styles - as its name suggests, it helps us modify styles. In the card above, a modifier was created to disable one of the buttons, i.e., making the button inactive and unclickable.

Here is the code to create the card above; take a deep look at it - the HTML and CSS code. Try to see how I implemented BEM when defining class names in the semantic HTML and how I structured the classes in CSS following each other from top-to-bottom (this is very important, try to always let your style be in a top-down approach).

See the Pen BEM by Shegz ( @shegz101 ) on CodePen .

For more understanding of the subject discussed, you can use these websites:

  • Official BEM Website

This article explored how the Block Element Modifier (BEM) methodology can aid in writing cleaner, more maintainable CSS code. We analyzed BEM’s history, principles, implementation, and best practices. Although some arguments against BEM exist, many people accept that it offers a clear and consistent approach to organizing CSS code.

I hope you will consider using BEM in your subsequent projects because of its benefits. The benefits of BEM, such as easier collaboration, faster development time, and reduced errors, make it a valuable tool in modern web development.

Call to action : I challenge developers to try implementing BEM in their next project and see the positive impact it can have. Remember to start with a solid foundation by naming and structuring your blocks, elements, and modifiers. With the BEM methodology, you can take your CSS coding skills to the next level and create more efficient and maintainable user interfaces.

I trust that you found this piece informative and enjoyable. If you have any questions, please don’t hesitate to ask them in the comment box below. Additionally, I would appreciate it if you could share, like, and comment. Thank you for reading.

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs and track user frustrations. Get complete visibility into your frontend with OpenReplay, the most advanced open-source session replay tool for developers.

Check our GitHub Repo

More articles from OpenReplay Blog

A dive into different types of testing tools for several purposes

Aug 30, 2022, 7 min read

Testing tools: Launchers and Structure Providers

{post.frontmatter.excerpt}

An overview of testing tools for many purposes

Aug 24, 2022, 9 min read

Testing tools: a Classification

Tiffany Brown

CSS Architecture: Block-Element-Modifier (BEM) & Atomic CSS

Share this article

CSS Architecture: Block-Element-Modifier (BEM) & Atomic CSS

Frequently Asked Questions (FAQs) on CSS Architecture: BEM and Atomic CSS

Block-element-modifier (bem).

bem methodology css

An element is a part of a block that performs a certain function. Elements are context-dependent: they only make sense in the context of the block they belong to.

A search block with text input and submit button elements

  • block names must be unique within a project
  • element names must be unique within a block
  • variations of a block—say, a search box with a dark background—should add a modifier to the class name
  • it’s easy for new team members to read the markup and CSS, and understand its behavior
  • adding more developers increases team productivity
  • consistent naming reduces the possibility of class-name collisions and side effects
  • CSS is independent of markup
  • CSS is highly reusable
  • keeps CSS trim by creating highly granular, highly reusable styles, instead of a ruleset for every component
  • greatly reduces specificity conflicts by using a system of low-specificity selectors
  • allows for rapid HTML component development once the initial rulesets are defined

The Case Against Atomic CSS

Bem versus atomic css, know when to go your own way, what is the main difference between bem and atomic css.

BEM (Block, Element, Modifier) and Atomic CSS are both methodologies for organizing and structuring CSS code. BEM focuses on a naming convention that makes CSS easier to read and understand. It divides the design into blocks, elements, and modifiers to create a clear, strict relationship between CSS and HTML. On the other hand, Atomic CSS is about writing small, single-purpose CSS classes that reflect visual function. It encourages reusability and aims to reduce the amount of code.

How does BEM improve CSS scalability?

BEM improves CSS scalability by providing a clear and strict relationship between CSS and HTML. It uses a specific naming convention that makes it easier to understand the relationship between different elements. This makes the code more maintainable and scalable, as it’s easier to add new features or modify existing ones without breaking anything.

Can I use BEM and Atomic CSS together?

Yes, it’s possible to use BEM and Atomic CSS together. Some developers find that combining the two methodologies brings the best of both worlds. BEM’s strict naming convention can be used to structure the CSS, while Atomic CSS’s single-purpose classes can be used to style individual elements. This combination can result in a highly organized and maintainable CSS codebase.

What are the benefits of using Atomic CSS?

Atomic CSS offers several benefits. It encourages reusability, which can significantly reduce the amount of CSS you need to write. It also promotes consistency in design, as the same classes are used across different components. Furthermore, Atomic CSS can make your stylesheets more manageable and easier to understand, as each class has a single, clearly defined purpose.

How does BEM handle CSS specificity issues?

BEM helps handle CSS specificity issues by encouraging developers to use class selectors instead of id selectors. This results in a flat specificity across the entire project, making it easier to override styles when necessary. Furthermore, BEM’s naming convention makes it clear which elements are related, reducing the likelihood of unintended style conflicts.

Is Atomic CSS suitable for large projects?

Yes, Atomic CSS is suitable for large projects. Its focus on reusability and single-purpose classes can help keep the CSS manageable, even as the project grows. However, it requires a disciplined approach to ensure that classes remain consistent and meaningful.

How does BEM help in team collaboration?

BEM’s clear and strict naming convention makes it easier for team members to understand the CSS code, regardless of when they joined the project. This can improve collaboration, as developers can easily understand and modify the code written by others.

What are the potential drawbacks of using Atomic CSS?

One potential drawback of Atomic CSS is that it can lead to a large number of classes in your HTML. This can make the HTML harder to read and understand. Additionally, Atomic CSS requires a disciplined approach to ensure that classes remain consistent and meaningful.

How can I start implementing BEM in my projects?

To start implementing BEM, you need to divide your design into blocks, elements, and modifiers. Then, use BEM’s naming convention to name your CSS classes. This will create a clear relationship between your CSS and HTML, making your code easier to read and maintain.

Can I use BEM or Atomic CSS with CSS preprocessors like Sass or Less?

Yes, both BEM and Atomic CSS can be used with CSS preprocessors like Sass or Less. These preprocessors can make it easier to manage your CSS, and they work well with the organizational principles of both BEM and Atomic CSS.

Tiffany B. Brown is a freelance web developer and technical writer based in Los Angeles. Brown offers web development and consulting services to larger agencies and small businesses. A former member of the Opera Software developer relations team, Brown is also co-author of SitePoint's JumpStart HTML5 book. She sporadically writes about web development technology on her blog . You can follow her on Twitter at @webinista .

SitePoint Premium

BEM by Example

06-12-17 Nathan Rambeck

BEM is a popular naming convention for CSS class names that we use widely here at Sparkbox. The fundamental concepts of BEM are simple and straightforward, but there are common errors those new to BEM make that this post seeks to explain through a series of examples.

bem methodology css

BEM (which stands for Block-Element-Modifier) is a naming convention standard for CSS class names. It has fairly wide adoption and is immensely useful in writing CSS that is easier to read, understand, and scale.

BEM naming provides three specific benefits:

It communicates purpose or function

It communicates component structure

It sets a consistent low-level of specificity for styling selectors

How It Works

A BEM class name includes up to three parts.

Block: The outermost parent element of the component is defined as the block.

Element: Inside of the component may be one or more children called elements.

Modifier: Either a block or element may have a variation signified by a modifier.

If all three are used in a name it would look something like this:

[block]__[element]--[modifier]

After that brief introduction, let’s look at some specific examples.

Component With No Elements or Modifiers

Simple components may only employ a single element and thus a single class which would be the block.

Component With A Modifier

A component may have a variation. The variation should be implemented with a modifier class.

Don’t use the modifier class by itself. The modifier class is intended to augment, not replace, the base class.

Component With Elements

More complex components will have child elements. Each child element that needs styled should include a named class.

One of the purposes behind BEM is to keep specificity low and consistent. Don’t omit class names from the child elements in your HTML. That will force you to use a selector with increased specificity to style those bare elements inside the component (see img and figcaption elements below). Leaving those classes off may be more succinct, but you will increase risks of cascade issues in the future. One goal of BEM is for most selectors to use just a single class name.

If your component has child elements several levels deep, don’t try to represent each level in the class name. BEM is not intended to communicate structural depth. A BEM class name representing a child element in the component should only include the base/block name and the one element name. In the examples below, note that photo__caption__quote is an incorrect usage of BEM, while photo__quote is more appropriate.

Element With Modifier

In some cases, you may want to vary a single element in a component. In those cases add a modifier to the element instead of the component. I’ve found that modifying elements is much less common and less useful than modifying entire components.

Style Elements Based on the Component Modifier

If you find yourself consistently modifying elements of the same component together in the same way, then consider adding the modifier to the base of the component and adjusting styles for each child element based on that one modifier. This will increase specificity, but it makes modifying your component much simpler.

Multi-word Names

BEM names intentionally use double underscores and double hyphens instead of single to separate Block-Element-Modifier. The reason is so that single hyphens can be used as word separators. Class names should be very readable, so abbreviation isn’t always desirable unless the abbreviations are universally recognizable.

BEM Will Make You Happy

If you are not using BEM currently, I would highly recommend using it on your next project. It may be different than what you’re used to, but I’m convinced you’ll quickly see the benefits it provides on projects both large and small. And, hopefully, these examples will help you to avoid some of the common mistakes made by most of us when first diving into this quirky naming convention.

Sparkbox’s Development Capabilities Assessment

Struggle to deliver quality software sustainably for the business? Give your development organization research-backed direction on improving practices. Simply answer a few questions to generate a customized, confidential report addressing your challenges.

Related Content

User-centered thinking: 7 things to consider and a free guide.

Want the benefits of UX but not sure where to start? Grab our guide to evaluate your needs, earn buy-in, and get hiring tips.

Get Email Updates

See everything in, more like this, of mice and bem: getting past common problems with css organization.

Philip Zastrow

Philip addresses four common misconceptions about BEM and explains how and why the CSS naming convention of Block Element Modifier helps solve organizational thinking around class names.

Thoughtful CSS Architecture

Nathan Rambeck

Nathan provides an introduction to CSS architecture that will help you design a structure for your code so your projects and teams can grow without becoming an unmanageable mess.

Why You Need to Refactor Your CSS

If you’re doing it right, anything you build on the web is constantly evolving. No matter how much planning you do, you’re going to need to refactor your CSS.

Want to talk about how we can work together?

Katie can help

A portrait of Vice President of Business Development, Katie Jennings.

Katie Jennings

Vice President of Business Development

  • Inna Belaya
  • Jun 18, 2018

BEM For Beginners: Why You Need BEM

  • 23 min read
  • Tools , Coding , CSS
  • Share on Twitter ,  LinkedIn

About The Author

Inna is a technical writer since 2008. For the last sevearal years she works in Yandex in BEM team. More about Inna ↬

Email Newsletter

Weekly tips on front-end & UX . Trusted by 200,000+ folks.

BEM makes your code scalable and reusable, thus increasing productivity and facilitating teamwork. Even if you are the only member of the team, BEM can be useful for you. Nevertheless, many developers believe that such a system approach like BEM puts additional boundaries on their project and makes your project overloaded, cumbersome, and slow.

We’ll be collecting all of the main aspects of BEM in a condensed form. This article helps you understand the basic ideas of BEM in just 20 minutes, and to reject prejudices that the system approach is detrimental to your project.

The Big BEM consists of Methodology , Technologies , Libraries , and Tools . In this article, we’ll talk more about the methodology itself because it is the concentrated experience of a huge number of developers and it brings a systematic approach to any project.

In order to show you some practical cases of BEM, we’ll touch on the BEM technologies and completely skip the libraries and tools.

From theory to practice:

The Main Reasons Why We Do Not Use Any Selectors Except Classes

  • Blocks And Elements

Modifiers And Mixes

Blocks in the file structure, non-evident advantages of the methodology, practical case: bem is not only for css, bem is a customizable system.

So, is BEM a hero or a villain? It’s up to you! But first, read the article.

One of the basic rules of the BEM methodology is to use only class selectors. In this section, we’ll explain why.

  • Why don’t we use IDs?
  • Why don’t we use tag selectors?
  • Why don’t we use a universal selector?
  • Why don’t we use CSS reset?
  • Why don’t we use nested selectors?
  • Why don’t we combine a tag and a class in a selector?
  • Why don’t we use combined selectors-
  • Why don’t we use attribute selectors?

We Don’t Use IDs (ID Selectors)

The ID provides a unique name for an HTML element. If the name is unique, you can’t reuse it in the interface. This prevents you from reusing the code.

Common Misconceptions

  • IDs are required for using JavaScript. Modern browsers can work with either IDs or classes. Any type of selector is processed at the same rate in the browser.
  • IDs are used with the <label> tag. If you place <label> inside a control, it doesn’t need an ID. Instead of <input id="ID"><label for="ID">Text</label> , simply use <label><input type="...">Text</label> .

We Don’t Use Tag Selectors

HTML page markup is unstable: A new design can change the nesting of the sections, heading levels (for example, from <h1> to <h3> ) or turn the <p> paragraph into the <div> tag. Any of these changes will break styles that are written for tags. Even if the design doesn’t change, the set of tags is limited. To use an existing layout in another project, you have to solve conflicts between styles written for the same tags.

An extended set of semantic tags can’t meet all layout needs, either.

An example is when the page header contains a logo. A click on the logo opens the main page of the site ( index ). You can mark it up with tags by using the <img> tag for the image and the <a> tag for the link.

To distinguish between the logo link and an ordinary link in the text, you need extra styles. Now remove underlining and the blue color from the logo link:

The logo link doesn’t need to be shown on the main page, so change the index page markup:

You don’t need to remove the underlining and the blue color for the <span> tag. So let’s make general rules for the logo link from different pages:

At first glance, this code seems all right, but imagine if the designer removes the logo from the layout. The selector names don’t help you understand which styles should be removed from the project with the logo. The “header a” selector doesn’t show the connection between the link and the logo. This selector could belong to the link in the header menu or, for example, to the link to the author’s profile. The “header span” selector could belong to any part of the header.

To avoid confusion, just use the logo class selector to write the logo styles:

We Don’t Use CSS Reset

CSS reset is a set of global CSS rules created for the whole page. These styles affect all layout nodes, violate the independence of components, and make it harder to reuse them.

In BEM, “reset” and “normalize” aren’t even used for a single block. Resetting and normalization cancel existing styles and replace them with other styles, which you will have to change and update later in any case. As a result, the developer has to write styles that override the ones that were just reset.

We Don’t Use The Universal Selector ( * )

The universal selector indicates that the project features a style that affects all nodes in the layout. This limits reuse of the layout in other projects:

  • You have to additionally transfer the styles with an asterisk to the project. But in this case, the universal selector might affect the styles in the new project.
  • The styles with an asterisk must be added to the layout you are transferring.

In addition, a universal selector can make the project code unpredictable. For example, it can affect the styles of the universal library components.

Common styles don’t save you time. Often developers start by resetting all margins for components ( * { margin: 0; padding: 0; } ), but then they still set them the same as in the layout (for example, margin: 12px; padding: 30px; ).

We Don’t Use Nested Selectors

Nested selectors increase code coupling and make it difficult to reuse the code.

The BEM methodology doesn’t prohibit nested selectors, but it recommends not to use them too much. For example, nesting is appropriate if you need to change styles of the elements depending on the block’s state or its assigned theme.

We Don’t Use Combined Selectors

Combined selectors are more specific than single selectors, which makes it more difficult to redefine blocks.

Consider the following code:

Let’s say you set CSS rules in the .button.button_theme_islands selector to do less writing. Then you add the “active” modifier to the block:

The .button_active selector doesn’t redefine the block properties written as .button.button_theme_islands because .button.button_theme_islands is more specific than .button_active . To redefine it, combine the block modifier selector with the .button selector and declare it below the .button.button_theme_islands because both selectors are equally specific:

If you use simple class selectors, you won’t have problems redefining the styles:

We Don’t Combine A Tag And A Class In A Selector

Combining a tag and a class in the same selector (for example, button.button ) makes CSS rules more specific, so it is more difficult to redefine them.

Let’s say you set CSS rules in the button.button selector. Then you add the active modifier to the block:

The .button_active selector doesn’t redefine the block properties written as button.button because button.button is more specific than .button_active . To make it more specific, you should combine the block modifier selector with the button.button_active tag.

As the project develops, you might end up with blocks with input.button , span.button or a.button selectors. In this case, all modifiers of the button block and all its nested elements will require four different declarations for each instance.

Possible Exceptions

In rare cases, the methodology allows combining tag and class selectors. For example, this can be used for setting the comments style in CMS systems that can’t generate the correct layout.

You can use the comment to write a text, insert images, or add markup. To make them match the site design, the developer can pre-define styles for all tags available to the user and cascade them down to the nested blocks:

We Don’t Use Attribute Selectors

Attribute selectors are less informative than class selectors. As proof, consider an example with a search form in the header:

Try using selector attributes to write the form styles:

In this example, you can’t tell for sure from the selector name that the styles belong to the search form. Using classes makes it clearer. Classes don’t have restrictions that prevent you from writing clearly. For example, you can write it like this:

Now the code is less ambiguous, and it’s clear that the styles belong to the search form.

But the nested selectors still make the CSS rules more specific and prevent you from transferring the layout between projects. To get rid of nesting, use BEM principles.

Summary : class is the only selector that allows you to isolate the styles of each component in the project; increase the readability of the code and do not limit the re-use of the layout.

CSS styles isolation is the most frequent start point of the BEM journey. But this is the least that BEM can give you. To understand how isolated independent components are arranged in BEM, you need to learn the basic concepts, i.e. Block, Element, Modifier, and Mix. Let’s do this in the next section.

The Basics Of BEM

Block and elements.

The BEM methodology is a set of universal rules that can be applied regardless of the technologies used, such as CSS, Sass, HTML, JavaScript or React.

BEM helps to solve the following tasks:

  • Reuse the layout;
  • Move layout fragments around within a project safely;
  • Move the finished layout between projects;
  • Create stable, predictable and clear code;
  • Reduce the project debugging time.

In a BEM project, the interface consists of blocks that can include elements . Blocks are independent components of the page. An element can’t exist outside the block, so keep in mind that each element can belong to one block only.

The first two letters in BEM stand for B locks and E lements. The block name is always unique. It sets the namespace for elements and provides a visible connection between the block parts. Block names are long but clear in order to show the connection between components and to avoid losing any parts of these components when transferring the layout.

To see the full power of BEM naming, consider this example with a form. According to the BEM methodology, the form is implemented using the form block. In HTML, the block name is included in the class attribute:

All parts of the form (the form block) that don’t make sense on their own are considered its elements. So the search box ( search ) and the button ( submit ) are elements of the form block. Classes also indicate that an element belongs to the block:

Note that the block’s name is separated from the element’s name with a special separator. In the BEM classic naming scheme , two underscores are used as a separator. Anything can work as a separator. There are alternative naming conventions , and each developer chooses the one that suits them. The important thing is that separators allow you to distinguish blocks from elements and modifiers programmatically.

Selector names make it clear that in order to move the form to another project, you need to copy all of its components:

Using blocks and elements for class names solves an important problem: It helps us get rid of nested selectors. All selectors in a BEM project have the same weight. That means it is much easier to redefine styles written according to BEM. Now, to use the same form in another project, you can just copy its layout and styles.

The idea of the naming of BEM components is that you can explicitly define the connection between the block and its elements.

Officially, “M” stands for M odifier, but it also implies one more important notion in BEM: “mix”. Both modifiers and mixes make changes to a block and its elements. Let’s take a closer look at this.

A modifier defines the look, state and behavior of a block or an element. Adding modifiers is optional. Modifiers let you combine different block features, as you can use any number of modifiers. But a block or an element can’t be assigned different values of the same modifier.

Let’s explore how modifiers work.

Imagine the project needs the same search form as in the example above. It should have the same functions but look different (for example, the search forms in the header and in the footer of the page should differ). The first thing you can do to change the appearance of the form is to write additional styles:

The header .form selector has more weight than the form selector, which means that one rule will override the other one. But as we have discussed, nested selectors increase code coupling and make reuse difficult, so this approach doesn’t work for us.

In BEM, you can use a modifier to add new styles to the block:

The line <form class="form form_type_original"></form> indicates that the block was assigned a type modifier with the original value. In a classic scheme, the modifier name is separated from the block or element name with an underscore.

The form can have a unique color, size, type, or design theme. All these parameters can be set with a modifier:

The same form can look different but stay the same size:

But the selectors for each modifier will still have the same weight:

Important : A modifier contains only additional styles that change the original block implementation in some way. This allows you to set the appearance of a universal block only once, and add only those features that differ from the original block code into the modifier styles.

This is why a modifier should always be on the same DOM node with the block and the element it is associated with.

You can use modifiers to apply universal components in very specific cases. The block and element code doesn’t change. The necessary combination of modifiers is created on the DOM node.

A mix allows you to apply the same formatting to different HTML elements and combine the behavior and styles of several entities while avoiding code duplication. They can replace abstract wrapper blocks.

A mix means that you host several BEM entities (blocks, elements, modifiers) on a single DOM node. Similar to modifiers, mixes are used for changing blocks. Let’s look at some examples of when you should use a mix.

Blocks can differ not only visually but also semantically. For example, a search form, a registration form and a form for ordering cakes are all forms. In the layout, they are implemented with the “form” block but they don’t have any styles in common. It is impossible to handle such differences with a modifier. You can define common styles for such blocks but you won’t be able to reuse the code.

You can use a mix to create semantically different blocks for the same form:

The .form class selector describes all styles that can be applied to any form (order, search or registration):

Now you can make a search form from the universal form. To do this, create an additional search class in the project. This class will be responsible only for the search. To combine the styles and behavior of the .form and .search classes, place these classes on a single DOM node:

In this case, the .search  class is a separate block that defines behavior. This block can’t have modifiers responsible for the form, themes, and sizes. These modifiers already belong to the universal form. A mix helps to combine the styles and behavior of these blocks.

Let’s take one more example where the component’s semantics is changed. Here is a navigation menu in the page header in which all entries are links:

The link functionality is already implemented in the link block, but the menu links have to differ visually from the links in the text. There are several ways to change the menu links:

  • Create a menu entry modifier that turns the entry into a link: <nav class="menu"> <a class="menu__item menu__item_link" href=""></a> <a class="menu__item menu__item_link" href=""></a> <a class="menu__item menu__item_link" href=""></a> </nav> In this case, to implement the modifier, you should copy the `link` block behavior and styles. This will lead to code duplication.
  • Use a mix of the `link` universal block and the `item` element of the `menu` block: <nav class="menu"> <a class="link menu__item" href=""></a> <a class="link menu__item" href=""></a> <a class="link menu__item" href=""></a> </nav> With the mix of the two BEM entities, you can now implement the basic link functionality from the `link` block and additional CSS rules from the `menu` block, and avoid code duplication.

External Geometry And Positioning: Giving Up Abstract HTML Wrappers

Mixes are used to position a block relative to other blocks or to position elements inside a block. In BEM, styles responsible for geometry and positioning are set in the parent block. Let’s take a universal menu block that has to be placed in the header. In the layout, the block has to have a 20px indent from the parent block.

This task has several solutions:

  • Write styles with indents for the menu block: .menu { margin-left: 20px; } In this case, the "menu" block isn’t universal anymore. If you have to place the menu in the page footer, you will have to edit styles because the indents will probably be different.
  • Create the menu block modifier: <div> <ul class="menu menu_type_header"> <li class="menu__item"><a href=""></a></li> <li class="menu__item"><a href=""></a></li> <li class="menu__item"><a href=""></a></li> </ul> </div> .menu_type_header { margin-left: 20px; } .menu_type_footer { margin-left: 30px; } In this case, the project will include two kinds of menus, although this is not the case. The menu stays the same.
"The indent from a parent block isn’t a feature of the nested block. It is a feature of the parent block. It has to know that the nested block has to be indented from the border by a certain number of pixels."
  • Use a mix. The information about nested block positioning is included in the parent block elements. Then the parent block element is mixed into the nested block. In this case, the nested block doesn’t specify any indents and can be easily reused in any place.

Let’s go on with our example:

In this case, external geometry and positioning of the menu block are set through the header__menu element. The menu block doesn’t specify any indents and can be easily reused.

The parent block element (in our case it is header__menu ) performs the task of the wrapper blocks responsible for external positioning of the block.

All BEM projects have a similar file structure . The familiar file structure makes it easier for developers to navigate the project, switch between projects, and move blocks from one project to another.

The implementation of each block is stored in a separate project folder. Each technology (CSS, JavaScript, tests, templates, documentation, images) is in a separate file.

For example, if the input block appearance is set with CSS, the code is saved in the input.css file.

The code for modifiers and elements is also stored in separate files of the block. This approach allows you to include in the build only those modifiers and elements that are necessary for the implementation of the block.

To improve the project navigation, combine block modifiers with multiple values in directories.

The file structure of any BEM project consists of redefinition levels (you can learn more on them over here ). Redefinition levels allow you to:

  • Divide the project into platforms;
  • Easily update the block libraries included in the project;
  • Use common blocks to develop multiple projects;
  • Change the design themes without affecting the project logic;
  • Conduct experiments in a live project.

Using blocks and storing all block technologies in the same folder makes it easy to move blocks between projects. To move all styles and behavior of the block together with the layout, just copy the block folder to the new project.

The Convenience Of Parallel Development

In BEM, any layout is divided into blocks. Because the blocks are independent, they can be developed in parallel by several developers.

A developer creates a block as a universal component that can be reused in any other project.

An example is the bem-components block library, which contains universal blocks, such as a link , button , and input field . It is easier to create more complex blocks from universal components. For example, a selector or checkbox .

Using blocks in project layout helps you save the time on integrating code written by several developers, guarantees the uniqueness of component names, and lets you test blocks at the development stage.

Testing The Layout

It is problematic to test the functionality of the whole page, especially in a dynamic project connected to a database.

In BEM, each block is covered by tests. Tests are a block implementation technology, like Javascript or CSS. Blocks are tested at the development stage. It is easier to check the correctness of one block and then assemble the project from tested blocks. After that, all you have to do is to make sure that the block wrapper is working correctly.

Customizable Build Of A Project

For convenient development, all blocks and technologies in a BEM project are placed in separate folders and files. To combine the source files into a single file (for example, to put all CSS files in project.css , all JS files in project.js , and so on), we use the build process.

The build performs the following tasks:

  • Combines source files that are spread out across the project’s file system;
  • Includes only necessary blocks, elements, and modifiers (BEM entities) in the project;
  • Follows the order for including entities;
  • Processes the source file code during the build (e.g. compiles LESS code to CSS code).

To include only the necessary BEM entities in the build, you need to create a list of blocks, elements, and modifiers used on the pages. This list is called a declaration .

Since BEM blocks are developed independently and placed in separate files in the file system, they don’t ‘know’ anything about each other. To build blocks based on other blocks, specify dependencies. There is a BEM technology responsible for this: the deps.js files. Dependency files let the build engine know which additional blocks have to be included in the project.

In the previous sections, all code examples are for CSS. But BEM allows you to modify the behavior of the block and its representation in HTML in the same declarative way like in CSS.

How To Use Templating In BEM

In HTML, the block markup is repeated every time the block appears on the page. If you create the HTML markup manually and then need to fix an error or make changes, you will need to modify the markup for every instance of the block. To generate HTML code and apply fixes automatically, BEM uses templates; blocks are responsible for the way they are presented in HTML.

Templates allow you to:

  • Reduce the time used for project debugging, because the template changes are automatically applied to all project blocks;
  • Modify the block layout;
  • Move blocks with the current layout to another project.

BEM uses the bem-xjst template engine which features two engines:

  • BEMHTML Transforms the BEMJSON description of the page to HTML. The templates are described in .bemhtml.js files.
  • BEMTREE Transforms data to BEMJSON. The templates are described in BEMJSON format in .bemtree.js files.

If templates aren’t written for the blocks, the template engine sets the <div> tag for the blocks by default.

Compare the declaration of the blocks and the HTML output:

Declaration:

To modify the menu block layout, you need to write templates for the block:

  • Let’s change the menu block tag: block('menu')( tag()('menu') // Set the "menu" tag for the menu block ) Modified HTML: <menu class="menu"> <!-- Replace the "div" tag with the "menu" tag for the "menu" block --> <div class="menu__item"> <div class="link"></div> </div> <div class="menu__item menu__item_current"> <div class="link"></div> </div> </menu> Similar to CSS, the template is applied to all "menu" blocks on the page.
  • Add an extra element ( menu__inner ) that works as an inner wrapper and is responsible for the layout of the elements in the menu block. Originally the menu__inner element wasn’t included in the declaration, so we have to add it when the templates are built. BEM templates are written in JavaScript, so you can also use JavaScript to add a new element to the template: block('menu')( tag()('menu'), content()(function() { return { elem: 'inner', content: this.ctx.content }; }) ) <menu class="menu"> <!-- Replace the "div" tag with the "menu" tag for the "menu" block --> <div class="menu__inner"> <div class="menu__item"> <div class="link"></div> </div> <div class="menu__item menu__item_current"> <div class="link"></div> </div> </div> </menu>
  • Replace tags for all inner and item elements: block('menu')( tag()('menu'), content()(function() { return { elem: 'inner', content: this.ctx.content } }), elem('inner')( tag()('ul') ), elem('item')( tag()('li') ) ) <menu class="menu"> <ul class="menu__inner"> <li class="menu__item"> <div class="link"></div> </li> <li class="menu__item menu__item_current"> <div class="link"></div> </li> </ul> </menu>
  • Set the a tag for all links on the page: block('menu')( tag()('menu'), content()(function() { return { elem: 'inner', content: this.ctx.content } }), elem('inner')( tag()('ul') ), elem('item')( tag()('li') ) ); block('link')( tag()('a') ); <menu class="menu"> <ul class="menu__inner"> <li class="menu__item"> <a class="link"></a> </li> <li class="menu__item menu__item_current"> <a class="link"></a> </li> </ul> </menu>
  • Modify the existing template. Rules in templates are applied in the same way as in CSS: a lower rule overrides a higher rule. Add new rules to the template, and change the link tag from a to span : block('link')( tag()('a') ); block('link')( tag()('span') ); <menu class="menu"> <ul class="menu__inner"> <li class="menu__item"> <span class="link"></span> </li> <li class="menu__item menu__item_current"> <span class="link"></span> </li> </ul> </menu>

BEM methodology provides you strict rules to create a system in your project. But at the same time, a lot of BEM rules can be customized. BEM methodology allows you to change the naming convention, choose the most convenient file structure or add any technologies you want to the block.

Now you can tune in the system and make your own superhero of BEM!

How To Get More Out Of BEM

To start learning BEM principles, visit our website . If you have any questions you’d like to ask the team, join our Telegram channel or open up a discussion in our BEM Forum .

Further Reading

  • Event Calendars For Web Made Easy With These Commercial Options
  • Vanilla JavaScript, Libraries, And The Quest For Stateful DOM Rendering
  • New CSS Viewport Units Do Not Solve The Classic Scrollbar Problem
  • CSS Blurry Shimmer Effect

Smashing Newsletter

Tips on front-end & UX, delivered weekly in your inbox. Just the things you can actually use.

Front-End & UX Workshops, Online

With practical takeaways, live sessions, video recordings and a friendly Q&A.

TypeScript in 50 Lessons

Everything TypeScript, with code walkthroughs and examples. And other printed books.

There are only two hard problems in Computer Science: cache invalidation and naming things — Phil Karlton

It is a known fact that the right styleguide can significantly increase development speed, debugging, and the implementation of new features in legacy code. Sadly, most CSS codebases are sometimes developed without any structure or naming conventions. This leads to an unmaintainable CSS codebase in the long term.

The BEM approach ensures that everyone who participates in the development of a website works with a single codebase and speaks the same language. Using proper naming will prepare you for the changes in design of the website.

Encapsulates a standalone entity that is meaningful on its own. While blocks can be nested and interact with each other, semantically they remain equal; there is no precedence or hierarchy. Holistic entities without DOM representation (such as controllers or models) can be blocks as well.

Parts of a block and have no standalone meaning. Any element is semantically tied to its block.

Flags on blocks or elements. Use them to change appearance, behavior or state.

Suppose you have block form with modifiers theme: "xmas" and simple: true and with elements input and submit , and element submit with its own modifier disabled: true for not submitting form while it is not filled:

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

BEM vs. SMACSS: Comparing CSS methodologies

bem methodology css

Let’s face it, CSS can be a real pain to work with if you don’t have a good methodology or architecture to follow. Writing a slew of different selectors all over the place isn’t the ideal strategy; it creates a lot of specificity-related problems and can make our codebase chaotic and debugging tough.

Bem vs smacss comparing css methodologies

Following a CSS methodology guarantees that everyone involved in the development process speaks the same language. This is especially important in large projects with several people, making it easier to scale the software and for new team members to quickly wrap their heads around the codebase.

In this article, we will be comparing two widely used CSS methodologies: Block, Element, Modifier (BEM) and Scalable and Modular Architecture for CSS (SMACSS). We’ll look at their similarities and how they ultimately stack up against each other.

What is BEM?

File structure, development time, scalability and support.

BEM is a simple naming convention that makes your frontend code easier to read, comprehend, work with, and scale. It is robust and explicit.

We all know how messy an HTML document can be when it’s not well structured. Add in a bad naming convention for CSS classes and you’ve got a codebase that’s difficult to understand, buggy, and even harder to scale.

Following the BEM naming convention makes it simple to structure not only our CSS file, but also our HTML document. We can think in a component-driven manner with independent code blocks and CSS selectors, making our code reusable and modular.

To use BEM, we only need to follow its naming convention!

  • The B stands for block. A block is a standalone entity. An example would be a card component
  • The E stands for element. An element is a part of a block that’s semantically tied to it and has no meaning on its own
  • The M stands for modifier. It is simply a flag that lets you modify the appearance or behavior of an element or block

Let’s see how all these come together in an example below:

In the BEM methodology, blocks only have a class name. You can see this in the example above, .card . Elements that are part of the block are prefixed with the block name, followed by double underscores and a name for the element. You can see this in the example above with .card__img , .card__desc , .card__buttons , and .card__button .

Lastly, modifiers are prefixed with the block name or element that they modify, like .card-current , .card__button-success , and .card__button-danger in our example.

What is SMACSS and how does it work?

SMACSS is a series of rules for categorizing CSS rulesets in order to make the CSS codebase more organized, clean, scalable, and modular. Following the SMACSS methodology, we can separate our CSS rulesets into five categories:

All CSS rulesets that give HTML elements their default styling are referred to as base rules. Instead of employing class or ID selectors, we use element, attribute, pseudo-class, child, or sibling selectors to define these rulesets. Sometimes we refer to these style rules as resets, since they reset the default styling of HTML elements.

On the basis of reuse, layout styles can be split into major and minor styles. The major components are those that establish the page’s structure, such as headers, footers, sidebars, body, and so on. The page layout is made up of several major components, referred to as layout rules. Modules, on the other hand, are the minor components that reside within the major components.

bem methodology css

Over 200k developers use LogRocket to create better digital experiences

bem methodology css

Modules are UI components that are segregated and distinct from one another. They are usually found within layout components but are sometimes inside other modules components. They are unaffected by other user interface modules or layouts. Examples would be an accordion, a modal or dialog, or a carousel.

CSS rulesets are used to specify styles for various states of a component. This essentially overrides a UI module’s default styling. For instance, a message toast component could be in a successful or unsuccessful state, and we can either display a red or green color to depict that. States are similar to modifiers in the BEM methodology.

The purpose of theme CSS rulesets is to create theme-specific styles. The theme-specific properties primarily override default colors and pictures.

BEM vs. SMACSS: Comparing developer experience

BEM follows a naming convention, telling developers how to give class names to elements. This provides a nice way to structure our HTML document and stylesheets. Although class names can get very long, they’re still clean and readable.

SMACSS also makes our codebase clean. Its categorization rule lets us know where style rules should be declared in a clear and concise manner, and its naming convention makes our HTML document clean and readable, seeing as class names are minimal.

Both methodologies are great when it comes to making sure our codebase is clean, readable, and easy to navigate.

How we structure files in our project folder is a really big deal. Let’s compare both methodologies so we can see how they each structure their files.

More great articles from LogRocket:

  • Don't miss a moment with The Replay , a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

The BEM methodology has three approaches to organizing your project folder:

You can find out how the three approaches work here . Following the BEM technique, you have to create new files for each block in your project, and as your project grows and additional blocks are added, your project directory might get cluttered, making development more difficult.

It doesn’t matter how large your project is; if you’re following the SMACSS methodology, you’ll have the same folder structure we saw in the SMACSS overview section above. It uses SMACSS categorization rules and defines how we structure our project folder.

In this methodology, your modules file is usually the largest as your project grows. This can make searching for modules a hassle, but I find that a simple Ctrl+F , or Command+F if you’re on a Mac, can help you quickly search for modules with ease.

On this point, I wouldn’t say there is clear winner between the two. For me, I’d prefer to search through a single file than a whole directory.

Unless you’re using a CSS preprocessor like Sass or Less, development can be a little slow when you’re using the BEM methodology. Having to declare class names following its naming convention can be a little time consuming. Here’s what I mean:

Notice how long the class name are? If we were to target those elements using regular CSS, it might be a little tasking and time consuming. Here’s what I mean:

This can be resolved if we were using a CSS preprocessor — in this case, Sass — so our code above would look like this:

We still have to write the class names on our HTML elements, so for every block, there would be a lot of prefixing the block name to its elements and modifiers.

At the core of SMACSS is categorization. It doesn’t really give you a strict naming convention to follow, it just tells you where to place similar style rules and gives developers the flexibility of naming elements. It advises that you prefix selectors according to their categorization, so, for example, layout style rules can be written as .l-example .

However, SMACSS doesn’t advise that you follow the same naming rule for modules, seeing as modules can grow exponentially alongside your project. It recommends that you prefix related elements within a module with their base name. For example, .base would be the module and .base-element would be the element within a module.

In my opinion, development time in SMACSS is a lot faster than BEM, seeing as you don’t have to write such long class selectors.

It’s difficult to say which of these two methodologies provides better scalability and support; BEM appears to provide more support, while SMACSS appears to be a more scalable alternative. Still, let’s try to make a comparison here.

Many claim that because class names can get incredibly long when using the BEM methodology, our HTML page can get really messy and difficult for new team members to navigate their way around the codebase. But I disagree. In my opinion, it is easier to quickly understand what is going on with BEM because new files are created for each block.

Further, BEM allows you to structure your code so that you can create reusable components, and you can change the appearance and behavior of components to fit the context they’re placed in using modifiers. Creating a new file for every block or component as your project begins to grow can be a bit too much and doesn’t help with scalability.

For someone joining a new project on a large team, SMACSS provides little support and can make it difficult to wrap your head around what’s happening. In terms of scalability, however, once you’re able to understand how SMACSS works, you start to see how its categorization of style rules helps you scale your project.

In this article, we looked two widely used CSS methodologies: BEM and SMACSS. No matter which one you choose to use in your projects, you will benefit from the advantages of more structured CSS and UI. Neither outshines the other in my opinion; it’s really dependent on personal preference.

Is your frontend hogging your users' CPU?

As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket .

LogRocket Dashboard Free Trial Banner

LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app, mobile app, or website. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web and mobile apps — start monitoring for free .

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)

bem methodology css

Stop guessing about your digital experience with LogRocket

Recent posts:.

Biome Adoption Guide: Overview, Examples, And Alternatives

Biome adoption guide: Overview, examples, and alternatives

Biome combines linters and formatters into one tools, helping developers write better code faster and with less setup and configuration.

bem methodology css

React Native layout management with Yoga 3.0

Explore layout management in your React Native apps with the latest release of React Native v0.74 and Yoga 3.0.

bem methodology css

A guide to JavaScript parser generators

Explore three JavaScript parser generator libraries and the benefits of creating custom parsers for specific project needs.

bem methodology css

Using Rust and Axum to build a JWT authentication API

Learn to build a basic JWT authentication system with Rust and Axum, including setting up the routes, handlers, and the middleware system.

bem methodology css

3 Replies to "BEM vs. SMACSS: Comparing CSS methodologies"

I’m really against any naming methodologies. Modern CSS-in-JS solutions simply remove this overhead. The best conventions are the ones that are not needed!

There should be an example of SMACSS in the article.

“and you can change the appearance and behavior of components to fit the context they’re placed in using modifiers.”

This is plain wrong because BEM does not allow cascading. So one would need to add the modifier to every element. This results in an extreme overhead of both HTML class attributes and matching css selectors.

Leave a Reply Cancel reply

IMAGES

  1. The Block Element Modifier (BEM) Naming Convention (Methodology)

    bem methodology css

  2. Use BEM with CSS

    bem methodology css

  3. How to Use BEM Methodology

    bem methodology css

  4. How to Make the Most of BEM for CSS Coding

    bem methodology css

  5. BEM Methodology In CSS: A Quick Start Guide

    bem methodology css

  6. CSS BEM Methodology: Quick Guide

    bem methodology css

VIDEO

  1. Will the Recent Rally in SPY End this Week?

  2. Quick Tips for Studying PMBOK Guide Chapters 1

  3. Fem Demo 2022

  4. What is #BEM (Block, Element, Modifier) and How can it be used with #Drupal Emulsify Twig

  5. [Explicando] RAPID: o que é? como aplicar (exemplo PRÁTICO) #productmanagement

  6. "MindBEMding

COMMENTS

  1. CSS / Methodology / BEM

    The BEM methodology doesn't recommend combining tags and classes in a selector. Combining a tag and a class (for example, button.button ) makes the CSS rules more specific, which makes it more difficult to override them. This leads to priority battles, in which stylesheets are loaded by overly complicated selectors.

  2. BEM 101

    The Block, Element, Modifier methodology (commonly referred to as BEM) is a popular naming convention for classes in HTML and CSS. Developed by the team at Yandex, ... In this CSS methodology a block is a top-level abstraction of a new component, for example a button: .btn { }. This block should be thought of as a parent.

  3. BEM

    BEM — Block Element Modifier is a methodology, that helps you to achieve reusable components and code sharing in the front-end. Introduction Naming FAQ. Introduction. ... BEM methodology gives your CSS code a solid structure that remains simple and easy to understand. Further Reading

  4. BEM

    BEM — Block Element Modifier is a methodology, that helps you to achieve reusable components and code sharing in the front-end. ... Independent blocks and CSS selectors make your code reusable and modular. Flexible. Using BEM, methodologies and tools can be recomposed and configured the way you like.

  5. How to Use BEM Methodology

    The primary purpose of BEM methodology is to make names of CSS selectors as informative and transparent as possible. Original BEM style is defined in this way: Block name is usually a single word like .header, but if you have longer block definition then it is divided with a single hyphen -:

  6. BEM Methodology In CSS: A Quick Start Guide

    BEM Overview. BEM (Block-Element-Modifier) is a CSS naming convention developed by the team at Yandex to improve scalability and maintainability in web development. Put simply, the idea of BEM is to "divide the user interface into independent blocks" by naming CSS classes in the following methodology: /* Block component */.

  7. Mastering BEM: A Detailed Guide to Using BEM CSS Methodology ...

    BEM is a powerful methodology that can help you create more maintainable and scalable CSS. By using BEM, you can make your code more consistent and understandable, both for yourself and others.

  8. CSS Architecture Block-Element-Modifier (BEM)

    The Block, Element, Modifier (BEM) methodology provides a structured approach to CSS architecture. It helps in creating reusable, maintainable, and scalable code. The main advantage of BEM is that ...

  9. Introduction to BEM

    BEM stands for Block Element Modifier, which is a popular CSS methodology used for front-end development. Its main goal is to help organize, maintain, and scale CSS code in large projects. This methodology breaks styles down into three main components: 1. Blocks. 2.

  10. BEM Methodology: A Comprehensive Guide to CSS Optimization

    BEM is a powerful CSS class naming methodology that improves code organization and maintainability. The fundamental idea behind BEM is to divide the user interface into self-contained blocks ...

  11. BEM Methodology

    BEM is a methodology, an approach and a naming convention to write better CSS styling and achieve consistent JS behaviour. BEM stands for Block, Element and Modifier. These three are called BEM Entities. BEM is not a W3C standard but it's recommended by those who have adopted it and reaped its benefits.

  12. CSS BEM Methodology

    What is BEM. BEM, which stands for Block, Element, Modifier, is a naming convention for CSS classes that aims to create more maintainable, scalable, and reusable CSS code. BEM divides web components into three different parts, including: Blocks: Represent independent, reusable components of a web page, like a header, a button, or a form.

  13. Writing cleaner CSS code with BEM

    This article explored how the Block Element Modifier (BEM) methodology can aid in writing cleaner, more maintainable CSS code. We analyzed BEM's history, principles, implementation, and best practices. Although some arguments against BEM exist, many people accept that it offers a clear and consistent approach to organizing CSS code.

  14. CSS Architecture: Block-Element-Modifier (BEM) & Atomic CSS

    BEM (Block, Element, Modifier) and Atomic CSS are both methodologies for organizing and structuring CSS code. BEM focuses on a naming convention that makes CSS easier to read and understand. It ...

  15. BEM by Example: Best Practices for BEM CSS Naming

    BEM by Example. BEM is a popular naming convention for CSS class names that we use widely here at Sparkbox. The fundamental concepts of BEM are simple and straightforward, but there are common errors those new to BEM make that this post seeks to explain through a series of examples. BEM (which stands for Block-Element-Modifier) is a naming ...

  16. BEM For Beginners: Why You Need BEM

    The BEM methodology is a set of universal rules that can be applied regardless of the technologies used, such as CSS, Sass, HTML, JavaScript or React. BEM helps to solve the following tasks: ... Practical Case: BEM Is Not Only For CSS. In the previous sections, all code examples are for CSS. But BEM allows you to modify the behavior of the ...

  17. BEM

    BEM — Block Element Modifier is a methodology, that helps you to achieve reusable components and code sharing in the front-end. Introduction Naming FAQ. ... Sadly, most CSS codebases are sometimes developed without any structure or naming conventions. This leads to an unmaintainable CSS codebase in the long term.

  18. BEM vs. SMACSS: Comparing CSS methodologies

    CSS rulesets are used to specify styles for various states of a component. This essentially overrides a UI module's default styling. For instance, a message toast component could be in a successful or unsuccessful state, and we can either display a red or green color to depict that. States are similar to modifiers in the BEM methodology. Theme